Testing APIs with RestClient in Visual Studio Code

visual studio code wallpaper

In this new post, I show a simple way for testing APIs with RestClient in Visual Studio Code. This is for me the test API week and you will see few post about it.

If you’ve been doing web development, you’re probably aware that a lot of our job revolves around data. Reading data, writing data, manipulating data and displaying it in the browser in a way that makes sense.

And the vast majority of that data is supplied from REST API endpoints: representational state transfer application programming interfaces (what a mouth full, hence REST API). In laymen’s terms: the data we want exists in some other service or database, and our application queries that service to retrieve the data and use it as we see fit.

My current tools

Now, I think a lot of us are using Postman for check the APIs. I have to say that now Postman is becoming heavy and slow with a lot of functionalities. Most of the functionalities are there because they want to make money. Unfortunately, in my point of view, the tool is not fast and easy to use as before.

So, I was looking around to find some simple alternative that I can use with my teams in an agile environment with developers in other languages (like R) without knowledge in .NET. Also, I don’t want them to start to learn NUnit, XUnit or Microsoft Tests. Plus, I like to have an option to share with the team the tests and each person can run the tests.

Visual Studio Code

In every computer Visual Studio Code is installed and this tool is very flexible, it is a good editor and every person knows how to use it. Also, it has a big marketplace. Why don’t look around and find something?

Install RestClient

After a quick search in the marketplace and look on the internet, I found RestClient, an extension to call APIs. It is each testing APIs with RestClient in Visual Studio Code, so let install it.

To find it, open the marketplace extension in VS Code (the block of squares on the left panel), type “rest client” into the search bar, then install the first result in the list (the author should be Huachao Mao).

Here’s a screenshot so you know you’ve gotten the right one.

Visual Studio Code RestClient - Testing APIs with RestClient in Visual Studio Code
Visual Studio Code RestClient

Start to use RestClient

For that, simply create a file at the root of your project that ends in .http. REST Client recognizes this and knows it’s supposed to be able to run HTTP requests from this file. The REST Client plugin requires just a plain text file with the extension .http or .rest. The basic syntax is very simple as following

### Request 1
[GET|POST] [REST API URL] # Request Line
[Request Headers]

[Request Body]

### Request 2
[GET|POST] [REST API URL]

[Request Headers]

[Request Body]

The file can contain multiple requests, each request is separated by ### delimiter (three or more consecutive #).

Request Line

First, the first line of the request is the Request Line. It contains the request method (GET or POST), space, and then followed by the API URL endpoint. For example, I like to see the result of a public service from DB-IP that returns same information about a specific IP. So, in my file I’m going to write

GET https://api.db-ip.com/v2/free/86.170.154.104
Send a request with RestClient - Testing APIs with RestClient in Visual Studio Code
Send a request with RestClient

Immediately after finishing to the URL with the verb, on top of it, a text appears: Send Request. If I click on it, the RestClient sends the request and in a new tab it shows the result

RestClient shows all the details of the request - Testing APIs with RestClient in Visual Studio Code
RestClient shows all the details of the request

Request Header

The lines immediately after the Request Line are Request Header. The supported syntax is the field-name: field-value format, each line represents one header. The Authentication also can be set in this Request Header section.

GET https://api.db-ip.com/v2/free/86.170.154.104 HTTP/1.1
Content-Type: application/json
Authorization: Bearer <access_token>

Variables

You can declare your File variables to keep the values and reuse them in the script such as API base endpoint, version with @variableName = variableValue syntax in a separate line from request block. Then the request can use the defined variable with {{variableName}} syntax. Please note that you do not need the "" or '' characters for a string value.

@baseUrl = https://api.db-ip.com
@version = 2

###

POST {{baseUrl}}/auth/oauth2/v{{version}}/token HTTP/1.1

###

@ip = 86.170.154.104
GET {{baseUrl}}/v{{version}}/{{ip}}

This is what I see in the Visual Studio Code and in the result.

RestClient with parameters
RestClient with parameters

Variables: Request Variables

You can declare Request Variables to get a request or response message content. The syntax is just # @name requestName on a line before the Request Line. Once the request is sent, the script can access response (or request) message information from {{requestName.(response|request).(body|headers).(*|JSONPath|XPath|Header Name)}} syntax.

Using the example, I like to read the countryName from the result of the API and call another API that has a parameter the name of a country. Because I don’t have a similar API, I use the same API passing the countryName only to verify if the country is what I expect. So, the code I wrote is

@baseUrl = https://api.db-ip.com
@version = 2

@ip = 86.170.154.104

# @name ipResponse

GET {{baseUrl}}/v{{version}}/free/{{ip}}
Accept: application/json

#### Variable Response

@countryName = {{ipResponse.response.body.$.countryName}}

### Test if the country name is passed

GET {{baseUrl}}/v{{version}}/free/{{countryName}}

Now, the response from the first call will be placed in the variable ipResponse. Then, I can read the body and the value for countryName. For that, I wrote line 13.

RestClient reads a value from the response
RestClient reads a value from the response

How you can see in the screenshot above, RestClient makes the api passing the value from the response. Obviously, in my case I didn’t expect a successful response but I verified the RestClient reads correctly a response and I can use it.

Request Body

The Request Body can be set by adding a blank line after Request Header and then place your HTTP request data in the next line. The request data can be various types of format such as JSON, XML, or key-value tuples.

One example is the RDP Auth Service which use application/x-www-form-urlencoded Content-Type. This content-type uses key-value tuples separated by &, with a = between the key and the value.

Send a POST request

Testing APIs with RestClient in Visual Studio Code seems quite easy. What if I want to send a POST, PUT or DELETE request?

Again, it is quite easy. I have only to specified the body like in this request:

POST https://localhost:3003/registerUser HTTP/1.1 
content-type: application/json

{
    "first_name": "Test", 
    "last_name": "User", 
    "email': "testing@email.com", 
    "username": "rest-client-tester", 
    "password": "testing123"
}

Ok, let’s go over what’s happening in the code snippet above.

The first thing REST Client needs in order to work, is the type of request to make and full URL path for the route its attempting to access. In this case, the request is a POST and the URL is https://localhost:3003/registerUser. The HTTP/1.1 at the end of the first line has something to do with the standards established by RFC 2616 but I’m not exactly sure if it’s necessary or not, so I left it there just to be safe.

Then, since this is a POST, there’s a JSON body to include in the request, note that there’s a blank line between Content-Type and the body — this is intentional and required by REST Client. So we have the required fields filled out, and then, above the POST a little Send Request option should appear. Mouse over it and click, and see what comes back.

Generate the code for the request

Once you’ve finalized your request in RestClient extension, you might want to make the same request from your source code. It allows you to generate snippets of code in various languages and libraries that will help you achieve this.

Once you prepared a request as previously, use shortcut Ctrl+Alt+C(Cmd+Alt+C for macOS), or right-click in the editor and then select Generate Code Snippet in the menu, or press F1 and then select/type Rest Client: Generate Code Snippet, it will pop up the language pick list, as well as library list. After you selected the code snippet language/library you want, the generated code snippet will be previewed in a separate panel of Visual Studio Code, you can click the Copy Code Snippet icon in the tab title to copy it to clipboard.

C# code generated from RestClient
C# code generated from RestClient

Wrap up

In conclusion, this is how testing APIs with RestClient in Visual Studio Code. It seems to me quite easy for everybody to test any APIs. What do you think?

Happy coding!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.