If you've used the dotnet 8 templates for creating an API you might have noticed a new file type, a .http
file. This blog post explores this new file and how we can use it.
.http
files allow you to send HTTP requests with support directly from within visual studio, vscode, rider among others. If you've used Postman and similar applications this will be very familiar.
After having mentioned Postman, you might be thinking why use it when I can just use Postman or similar applications. Here are a few pros I could think of:
Here is an example I created for demonstrating GET, POST, PUT & DELETE requests taken from this example github repo that I created on GitHub.
@base_address = http://localhost:5295
GET {{base_address}}/todos/
Accept: application/json
###
GET {{base_address}}/todos/{{$guid}}
Authorization: Basic {{$dotenv Authorization}}
Accept: application/json
###
POST {{base_address}}/todos/
Authorization: Basic {{$dotenv Authorization}}
Content-Type: application/json
{
"id": "{{$guid}}",
"title": "Todo Title ({{$timestamp}})",
"isComplete": false
}
###
@todo_id = {{$guid}}
PUT {{base_address}}/todos/{{todo_id}}
Authorization: Basic {{$dotenv Authorization}}
Content-Type: application/json
{
"id": "{{todo_id}}",
"title": "Todo Title ({{$timestamp}})",
"isComplete": false
}
###
DELETE {{base_address}}/todos/{{$guid}}
Authorization: Basic {{$dotenv Authorization}}
Accept: application/json
This HTTP file performs the following actions:
If you want to get started straight away you can get the source code here or can git clone
git clone https://github.com/reggieray/http-file-examples.git
In order to demonstrate features of .http
files, I created a mock minimal API with a RESTful looking endpoint. I added BasicAuthentication to the minimal API so the example could demonstrate setting auth headers. Basic authentication is implemented with a hardcoded username (admin) and password (admin). The API requires this authentication for endpoints marked with the [Authorize] attribute.
/todos
(GET): Retrieves a list of Todo items./todos/{id}
(GET): Retrieves a specific Todo item by ID./todos
(POST): Creates a new Todo item./todos/{id}
(PUT): Updates an existing Todo item./todos/{id}
(DELETE): Deletes a Todo item by ID.Below I'll demonstrate two ways of running the .http
files.
It's worth mentioning that I added a .env
file which can be used to get variables for the .http
file. In the Microsoft documentation it mentions using $dotEnv
, I found this didn't work for me, but using $dotenv
did. It's also worth noting I committed this file in for demo purposes. I would advise not to commit any information that has sensitive information.
Below I have included some GIFs of the usage from each respective IDE.
For Visual Studio you'll need Visual Studio 2022 version 17.8 or later with the ASP.NET and web development workload installed.
For VSCode you'll need the REST Client extension.