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.
### GET by Id
GET {{HostAddress}}/employees/{{createEmployee.response.body.$.id}}
Accept: application/json
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"
}
More read:
Use .http files in Visual Studio 2022
Use .http files in Visual Studio 2022
Hope this helps.
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment