Tuesday, September 19, 2023

Visual Studio 2022: HTTP Files and Variables

In this post, let's get to know some different ways to manage variables within HTTP Files.

Let's consider the following simple API.
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

WebApplication app = builder.Build();

app.MapGet("/users/{userId}", (int userId) =>
{
    return userId;
});

app.Run();

1. Use Inline Variables


You can define the variables in the .http file itself as follows
@HostAddress = http://localhost:5179
@userId = 1

GET {{HostAddress}}/users/{{userId}}
Accept: application/json
In-line variable

2. Use an Environment File


You can define an environment file with the name httpenv.json. The file can be in the same folder as in the .http file or a folder above it. Visual Studio will look for that file in the folder where the HTTP file exists. If it’s not found, Visual Studio will look through the parent directories to find it. When a file is found named httpenv.json, Visual Studio will stop searching for the file. The nearest file to the HTTP file found will then be used.

Here, I am just going to add httpenv.json next to the .http file.
{
  "development": {
    "userId": 2
  },
  "test": {
    "userId": 3
  }
}
Now I am closing and opening up the .http file (in order for the environment file to be picked), removing @userId = 1 defined in the .http file. Now because of the httpenv.json, I can see the environments in a dropdown as follows.
Environments
Now based on the environment we are selecting, I will get different values.
Environment: development
Environment: test

3. Use a user-specific environment file


You can also add a user-specific environment file named httpenv.json.user, next to the httpenv.json file.
{
  "development": {
    "userId": 4
  }
}
And now when you execute the request, you can see the following output.
User-specific environment file
The order of precedence for the variables is below. Once a match is found that value will be used, and other sources ignored.
  1. Variable declared in the .http file
  2. Variable declared in the httpenv.json.user file
  3. Variable declared in the httpenv.json file
Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment