Convenient API Testing – IntelliJ IDEA’s HTTP Client

Convenient API Testing – IntelliJ IDEA’s HTTP Client

IntelliJ IDEA Ultimate provides a powerful alternative to common API tools such as Postman, Rest-Assured, cUrl etc. through an elaborate embedded HTTP Client.

API tools often times have an unnecessary steep learning curve, coupled with the tendency to do little in terms of developer-friendliness.

This is where IntelliJ IDEA’s HTTP Client really shines due to its simplicity and ease of use. It facilitates Web Service testing by leveraging easily accessible .http and .rest files without being required to leave the IDE.

For simplicity’s sake, we will henceforth only consider .http files.

What are .http Files?

.http files are at the heart of the client. They simply store the HTTP Requests for execution.
Here, a distinction is made between scratch and physical files.

Scratch files are not stored inside the project, whereas physical files are. Scratch files are handy for local development, but are not tracked by your Version Control System.

On the other hand, physical .http files are extremely useful since they can be stored inside a VCS repository and are essentially easily modifiable, functional and declarative API documentation akin to OpenAPI and Swagger. Easily executable by pressing the Run Button.

This facilitates testing the API of various services without the need to cumbersomely import configurations or collections. Having to ask which credentials one needs and subsequently how to obtain them to converse with certain endpoints impedes the general workflow.

The .http files solve this issue by having everything set up and ready to go.

Getting started

First, we have to create a .http file.

Manually create a file with an extension of .http

Generating an .http file is as easy as clicking an icon on a given Requesthandler method

Clicking the green icon will create a generated-requests.http file

or selecting it on the Endpoints Tab:

The Endpoints tab gives you an overview of your API

This will automatically generate a .http scratch file encompassing the url of the endpoint.

A generated.requests.http scratch file with the added URL

Syntax

For those experienced in working with common API tools the syntax should feel familiar and intuitive. As shown in the official documentation:

https://www.jetbrains.com/help/idea/http-client-in-product-code-editor.html#composing-http-requests

###
Method Request-URI HTTP-Version
Header-field: Header-value

Request-Body

### is used as a separator for multiple Requests in a file

As an example, we will take a look at a regular GET Request.

„Run all requests in file“ for Batch Execution

The #@name annotation assigns an identifier to a Request. Enabling you to execute the Request through the “Run anything” window, without requiring to open the corresponding .http file.

Name Resolution

Naturally, IntelliJ IDEA’s HTTP Client supports variable declaration and resolution.

Simply put the term into curly braces to declare it as a variable:

{{Variable}}

Create an environment file containing the desired values.

Regular environment files should be used to store values for public use, whereas private environment files should store sensitive data like credentials, tokens etc.

A common use case for instance would be resolving the schema, host and port for a respective stage. The following examples are merely suggestions.

Example HTTP Request with environment variables:

Flexible Parameterization

Environment for public use:

Example http-client.env.json

Private environment for sensitive data like credentials, tokens, secrets etc.:

Example http-client.private.env.json

After pressing the run icon, you will be able to select your preconfigured environment.

Select an environment

The variables will be resolved by their respective environment values.

Dynamic Variables are declared like this:

{{$Variable}}
POST Request with a random integer as Path Variable

Following Redirects

Per default, any Request with an HTTP status of 302 FOUND will be followed. For this example I will use Java in combination with Spring-Boot.

A DemoController with a Requestmapping of „/api“ with the following endpoints is set up and called:

Redirection endpoint of the DemoController

And we’ve been redirected!

This behavior can be disabled by tagging the Request with @no-redirect

Image Previews

If an endpoint responds with an image, a preview of said image is viewable.

Instead of human unreadable data, we get a coherent image.

Given following Endpoint providing an image of coffee:

A Java Endpoint

And a Request to retrieve the data:

GET Request for the Image

We receive this image of coffee!

Coffee Shop Love

The Preview Feature also works with QR-Codes:

Endpoint:

Serving the QR-Code with ZXing and hiding the content with impeccable editing skills

Request:

Requesting the QR-Code

QR-Code Preview:

QR-Code Preview

Working with the Response

The HTTP Client allows a great deal of control regarding the handling of the Response.

Accessing and traversing the Response in json-format is pretty straightforward and nested objects can be accessed arbitrarily deep. The Request can be tested and traversed with JavaScript.

The Request:

Logging out Response Header and Body Data

The response can be read from a file, as well as written to a file.

#Syntax for JavaScript code
> {% JavaScript code %}
#Read data from file
< filepath
#Create and saves the Response into the declared filepath and file
>> filepath
#Rewrite the Response into the declared filepath and file
>>! responses/ip.json

The Response Body:

Response Body of the GET demoData Endpoint

Our logs are shown within the Response Handler tab:

IntelliJ IDEA’s HTTP Client provides testing capabilities as well.

A simple test of our previous example:

Testing Response Header and Body

Returning the test results:

1 failed, 4 passed

Note that the test failed due to differing types coupled with the strict equality operator. A way to solve this issue would be by using the „==“ operator.

However, the Response Date test is obviously error prone since the time between Request and test execution might differ as well.

client.global

client.global acts as a de facto global context data layer. This adds a great deal of flexibility in regard to the application of the HTTP Client.

For instance, setting a part of the Response to reuse it later:

# Setting a global variable in the client.global context

> {%
    client.global.set("global_variable", response.body.global_variable);
%}

{{global_variable}} to reuse the set global variable

Authentication: Common usecases

In the following section, we will take a look at common applications of the HTTP Client in an authentication setting. Starting with a Request for Basic Authentication.

Basic Auth:

Basic Auth with environment variables

Sensitive data like username and password can be resolved from the private environment file, while the schema, host and port part can be provided by the regular environment file.

OAuth 2.0:

Getting a Token from the Authorization Server and requesting the Resource Server

The OAuth 2.0 example demonstrates how client.global can be used to acquire the Bearer Token from an Authorization Server such as Keycloak and saved globally.

Subsequently the Token will be used to authenticate a Post Request to the actual Resource Server.

Cookie-based Login:

Cookies

In a Login scenario, Cookies from the Response Header can be saved into global context and sent in the Header of a separate Request for example to delete session related data.

Conclusion

In summary, IntelliJ IDEA’s HTTP Client improves the developer-experience in regard to API-Testing tremendously.

It combines strengths of other API tools without sharing most of their weaknesses.

The HTTP Client is compact (all within the IDE), ergonomic, yet powerful and I would recommend giving it a chance.

Note however, that the Ultimate License is a prerequisite for using this feature.

What I presented today is merely a fraction of the functionalities of the Client.

(It also supports gRPC Requests, Data Streaming and much more)

I suggest following these links for further information:

The Official documentation:

https://www.jetbrains.com/help/idea/http-client-in-product-code-editor.html

Amazing demonstration by Yuriy Artamonov hosted by Mala Gupta:

https://youtu.be/VMUaOZ6kvJ0

Copyright © 2022 JetBrains s.r.o., used with permission. IntelliJ IDEA and the IntelliJ IDEA logo are registered trademarks of JetBrains s.r.o.

Schreibe einen Kommentar