Monday, February 10, 2025

Visual Studio 2022: HTTP Files and Request Variables

It's a very common scenario that we want to call an endpoint and use the result in subsequent requests. In this post, let's see how we can make use of Request Variables in .http files in Visual Studio 2022 to achieve that. Request Variable is a special kind of a variable (see my previous post for use of variables Visual Studio 2022: HTTP Files and Variables).

So let's start. The first step is to give a request a name.
@HostAddress = http://localhost:5200

### CREATE
# @name createEmployee

POST {{HostAddress}}/employees
Content-Type: application/json
{
   "firstName": "John",
   "lastName": "Doe"
}
Here, the comment: # @name createEmployee which is located just before the request specifies the name of the request. You can use following syntax if you prefer, which is also valid.
// @name createEmployee
Now we can reference this particular named request (createEmployee) using following syntax.
{{<requestName>.(response|request).(body|headers).(*|JSONPath|XPath|<headerName>)}}
For example, say the above endpoint is returning a JSON response, something like the following.
POST: Employee
Now I can use the returned id to Get the employee by Id.
### GET by Id
GET {{HostAddress}}/employees/{{createEmployee.response.body.$.id}}
Accept: application/json
GET: Employee
I can even use the request variable in the request body. Say I want to update the existing employee with a different lastName.
### UPDATE
PUT {{HostAddress}}/employees/{{createEmployee.response.body.$.id}}
Content-Type: application/json
{
    "id": "{{createEmployee.response.body.$.id}}",
    "firstName": "{{createEmployee.response.body.$.firstName}}",
    "lastName": "Bloggs"
}
PUT: Employee

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment