Dev

Testing APIs and reusing JWTs in IntelliJ HTTP Client

Keep HTTP requests in Git, inject JWTs from login responses, test multipart uploads, and run IntelliJ HTTP Client scenarios from the ijhttp CLI.

Testing APIs and reusing JWTs in IntelliJ HTTP Client

Copying a JWT out of a login response broke my flow every time I tested an authenticated API. Keeping the request and its response handler in an IntelliJ .http file let me run the whole sequence from the editor.

The examples use IntelliJ IDEA Ultimate 2024.1 and JetBrains’ ijhttp CLI.

Keep API scenarios next to the code

A separate Postman collection meant updating two places every time I changed an endpoint or added a required field. A text-based .http file can live in the same Git repository as the endpoint. When a pull request changes an API contract, reviewers can see the request change in the diff and run it from the IDE.

ConcernIntelliJ HTTP ClientPostman
Version historyText files in Git and reviewable diffsWorkspace synchronization or JSON export
AccessIDE integration in Ultimate and a separate free CLIFree plan and a GUI that works for non-developers
Environment valuesShared and private JSON filesWorkspace variables and Vault
Related workflowsJavaScript assertions and a CI runnerMock servers and documentation tools

I use .http files when the team primarily works in the codebase and wants to run the same requests in CI. A shared GUI or an API mock server can still be a better fit when product or QA teammates need direct access.

Split shared settings from private credentials

I track base URLs and test account names in http-client.env.json. I keep passwords and API keys in http-client.private.env.json. The client merges properties under the selected environment name and gives the private file precedence for duplicate keys. Both files should use the same keys for environments such as local and dev.

http/http-client.env.json

1
2
3
4
5
6
7
8
9
10
11

{
  "local": {
    "baseUrl": "http://localhost:8080",
    "testEmail": "dev@example.com"
  },
  "dev": {
    "baseUrl": "https://dev-api.example.com",
    "testEmail": "dev@example.com"
  }
}

http/http-client.private.env.json

1
2
3
4
5
6
7
8
9

{
  "local": {
    "testPassword": "local-dev-password"
  },
  "dev": {
    "testPassword": "dev-server-password"
  }
}
# .gitignore
**/http-client.private.env.json
.idea/httpRequests/

The IDE’s .idea/httpRequests/ history may contain bearer tokens and response bodies. Ignore it along with the private environment file. If a credential was pushed, rotate it and follow your repository’s procedure for removing it from history.

An example file with empty secret fields is enough to tell teammates which private variables they need. CI should obtain the actual values from its secret store. Make sure your scenario targets the intended test environment before running a request that changes data.

Capture the access token from the login response

A > {% ... %} JavaScript response handler runs after its request. It can validate a login response, store the access token in client.global, and make that token available to later requests. Separating requests with ### keeps the login sequence and protected request together.

flowchart TD
    A["Load environment variables"] --> B["Send login request"]
    B --> C["Run response handler"]
    C --> D["Store access token"]
    D --> E["Send authenticated request"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
### 1. Log in and store the JWT
POST {{baseUrl}}/api/auth/login
Content-Type: application/json

{
  "email": "{{testEmail}}",
  "password": "{{testPassword}}"
}

> {%
    client.test("Login succeeds (200 OK)", function () {
        client.assert(response.status === 200, "Expected 200, received " + response.status);
        client.assert(response.body.accessToken !== undefined, "Missing accessToken");
    });

    client.global.set("accessToken", response.body.accessToken);
%}

### 2. Fetch the current member with the stored JWT
GET {{baseUrl}}/api/members/me
Authorization: Bearer {{accessToken}}
Accept: application/json

When the response advertises application/json, the HTTP Client exposes a parsed object as response.body. That gives the handler direct access to accessToken without JSON.parse(). Later requests, including requests in other .http files in the same client session, can expand {{accessToken}} in the authorization header.

client.global is session state. Restarting the IDE or launching a fresh ijhttp process clears it. Run the login before protected requests and pay attention to its test result if you are running requests one by one. A stale token from an earlier IDE run can obscure a failing login.

Assert the response and upload a file

client.test() groups related assertions, and client.assert() marks a test as failed when its condition is false. IntelliJ shows the results in the Services window. For a multipart request, < ./fixtures/avatar.png reads a local file relative to the request file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
### Upload a profile image and metadata
POST {{baseUrl}}/api/members/me/profile-image
Authorization: Bearer {{accessToken}}
Content-Type: multipart/form-data; boundary=WebAppBoundary

--WebAppBoundary
Content-Disposition: form-data; name="metadata"
Content-Type: application/json

{
  "displayName": "Namju Kim",
  "isPublic": true
}
--WebAppBoundary
Content-Disposition: form-data; name="file"; filename="avatar.png"
Content-Type: image/png

< ./fixtures/avatar.png
--WebAppBoundary--

> {%
    client.test("Upload succeeds and returns an image URL", function () {
        client.assert(response.status === 200 || response.status === 201, "Upload failed: " + response.status);
        client.assert(response.contentType.mimeType === "application/json", "Expected a JSON response");
        client.assert(response.body.imageUrl && response.body.imageUrl.startsWith("https://"), "Missing HTTPS imageUrl");
    });
%}

The multipart boundary named in the request header must match every part separator. Leave one empty line between the part headers and the body, and end the request body with --WebAppBoundary--. With a Spring MVC endpoint that uses @RequestPart for a JSON DTO and a file, giving the metadata part its own Content-Type: application/json lets Spring select the JSON converter. A missing content type can lead to a 415 response.

To reference the project root explicitly, use < {{$projectRoot}}/http/fixtures/avatar.png. Keeping the fixture path relative makes the request portable to another checkout.

Run the same request file in CI

JetBrains’ ijhttp runs the scenario from a terminal. On macOS, the CLI can be installed through Homebrew.

1
2
3
4
5
6
7
# Install through Homebrew and run the scenario
brew install ijhttp

ijhttp --env-file http/http-client.env.json \
       --private-env-file http/http-client.private.env.json \
       --env dev \
       http/auth-and-profile.http

The Docker image is another option when your CI runner already has Docker. It resolves the request paths under the mounted /workdir directory.

1
2
3
4
5
6
7
8
9
# Run in Docker and produce a JUnit report
docker run --rm -i \
  -v "$PWD:/workdir" \
  jetbrains/intellij-http-client \
  --env-file http/http-client.env.json \
  --private-env-file http/http-client.private.env.json \
  --env dev \
  --report \
  http/auth-and-profile.http

With --report, the CLI produces a JUnit XML report at reports/report.xml. The runner can publish that file alongside the build log and fail the job when assertions fail. Run both the IDE and CLI version of the scenario when first adding it to CI. Check that login runs first, the private values resolve, and the upload path works relative to the checkout.

References

JetBrains HTTP Client CLI documentation

This post is licensed under CC BY 4.0 by the author.