Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Test Plans and Samplers

Testing REST APIs and JSON with JMeter

Test REST APIs with JMeter: build CRUD requests with JSON bodies, set headers and auth, extract ids with the JSON Extractor and chain create, read, update and delete calls.

Most modern load tests target APIs rather than HTML pages. REST APIs are friendly to JMeter: requests are plain HTTP, bodies are JSON, and the interesting part is chaining calls, where the response of one call (an id, a token) feeds the next. This lesson builds a typical create, read, update, delete flow.

Honesty note. JMeter cannot run here. The plan elements and field names are real. The runnable blocks are stand-ins: a tiny in-memory fake API and a JSONPath-like extractor written in JavaScript to show the logic of "extract id, then reuse it".

The scenario

We test a hypothetical Tasks API at https://api.example.test that you own or may test:

Step Request Expect
1 POST /tasks with JSON { "title": "Buy milk" } 201 and a JSON body containing id
2 GET /tasks/{id} 200 and the same title
3 PUT /tasks/{id} with { "title": "Buy oat milk", "done": true } 200
4 DELETE /tasks/{id} 204
5 GET /tasks/{id} again 404
sequenceDiagram
  participant T as Thread
  participant A as API
  T->>A: POST /tasks {title}
  A-->>T: 201 {id: 17}
  Note over T: JSON Extractor saves taskId = 17
  T->>A: GET /tasks/17
  A-->>T: 200
  T->>A: DELETE /tasks/17
  A-->>T: 204

The extractor turns a server-generated id into a per-thread variable used by later requests.

Plan structure

TEXT
Test Plan
โ”œโ”€โ”€ HTTP Request Defaults    (https, api.example.test)
โ”œโ”€โ”€ HTTP Header Manager      (Content-Type: application/json, Accept: application/json)
โ””โ”€โ”€ Thread Group
    โ”œโ”€โ”€ 01 Create task       POST /tasks        (+ JSON Extractor, + Response Assertion 201)
    โ”œโ”€โ”€ 02 Read task         GET  /tasks/${taskId}
    โ”œโ”€โ”€ 03 Update task       PUT  /tasks/${taskId}
    โ”œโ”€โ”€ 04 Delete task       DELETE /tasks/${taskId}
    โ””โ”€โ”€ 05 Read deleted      GET  /tasks/${taskId}  (assert 404)

Each sampler uses Body Data where there is a payload. Because the Header Manager sits above them, they all send the JSON headers.

Request bodies with variables

For the create step, Body Data might be:

JSON
{ "title": "Task ${__threadNum}-${__UUID}", "priority": ${__Random(1,5,)} }

Every thread then creates distinct tasks. Unique data matters: many systems have uniqueness rules, and identical data can hit caches unrealistically.

Extracting values with the JSON Extractor

Add a JSON Extractor (Add > Post Processors > JSON Extractor) as a child of the create request:

Field Value
Names of created variables taskId
JSON Path expressions $.id
Match No. 1 (first match; 0 random; -1 all)
Default Values NOT_FOUND

Always set a default value. If the extraction fails, the variable becomes NOT_FOUND, and a later request to /tasks/NOT_FOUND fails visibly, and you can assert on it, instead of silently reusing a stale value from an earlier loop.

Common JSON Path expressions:

Expression Selects
$.id Top-level field id
$.data.items[0].sku First item's sku
$.items[*].id All ids (use Match No. -1 to get ids_1, ids_2...)
$.items[?(@.price > 10)].id Ids of items with price above 10

Because JMeter supports a Groovy/JSR223 alternative, very complex parsing can be done in code, but a JSON Extractor is quicker to read and review.

Asserting on JSON

Use JSON Assertion (Add > Assertions > JSON Assertion): JSON Path $.title, tick Validate against expected value and enter the value, or check only that the path exists. Combine it with a Response Assertion on the status code. Assertions are explored in depth in Assertions.

Authentication

Common patterns:

  • API key: add a header, for example X-Api-Key: ${__P(apiKey,)}; pass the key with -JapiKey=... so it is not saved in the plan.
  • Bearer token: a login request with a JSON Extractor on $.access_token, then a header Authorization: Bearer ${token} on later requests (build this header in the Header Manager).
  • Basic auth: an HTTP Authorization Manager with a base URL, username and password, or a manually built Authorization: Basic header.

Keep secrets out of version control: use properties, environment-specific files that are git-ignored, or a secrets store, and only test accounts.

Stand-in: create, extract, reuse

JS Stand-in: chain create, read, update, delete with an extractor

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Experiment: change the extraction path to $.identifier. The variable becomes NOT_FOUND and every following step fails, which is exactly the signal the default value is designed to give.

Load-test design for APIs

  • Think about state. Create tests leave data behind; clean up in the same flow or a tearDown Thread Group.
  • Avoid collisions. Use per-thread data so threads do not update the same record unless contention is the thing you test.
  • Test the ratio. Real APIs see many more reads than writes; model a realistic mix with a Throughput Controller or several Thread Groups.
  • Mind rate limits. Test environments should have limits relaxed or you will measure the limiter, not the service.
  • Measure what matters. Group multi-call flows with a Transaction Controller so you see the time of "place an order" as a whole (Logic controllers).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which header must accompany a JSON request body?

    The Content-Type header tells the server how to parse the body.
  2. 2. Why set a default value in a JSON Extractor?

    A default such as NOT_FOUND makes failures obvious and testable.
  3. 3. Which JSON Path selects the id field at the top level?

    JMeter's JSON Extractor uses JSONPath, where $.id selects the top-level id.
  4. 4. Where should an API key preferably come from?

    Passing secrets as properties keeps them out of the committed .jmx file.

Summary

  • REST tests chain calls: create, extract an id, then read, update and delete using ${id}.
  • Use a Header Manager for content type, Body Data for JSON, and variables for unique data.
  • JSON Extractor with a default value makes extraction failures visible.
  • Keep secrets in properties, use test accounts, and clean up created data.
  • Group multi-call flows so you can measure business transactions.

Next: Logic Controllers