Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท Protocols and APIs

HTTP Requests, Bodies and Responses in k6

Send GET, POST, PUT and DELETE requests with k6/http, build JSON and form bodies, set headers and tags, and read status, body and timing details from each response.

Almost every k6 script is built around the k6/http module. It turns one function call into one HTTP request and hands you back a response object that you can check, measure and parse. If you understand requests and responses well, everything else in k6 (checks, thresholds, scenarios) becomes much easier to read.

Honesty note. k6 is a standalone Go binary and cannot run inside this website. Real k6 scripts in this lesson are shown as read-only js blocks. The runnable examples use Node.js with a tiny local HTTP server and a small http stand-in that mimics the shape of k6's API, so you can experiment with the ideas. The stand-ins are labelled and are not k6.

The basic calls

In k6 you import http and call a method named after the HTTP verb:

JavaScript
import http from 'k6/http';

export default function () {
  const res = http.get('https://api.example.test/items');
  console.log(res.status);
}

The signatures are small and regular:

Call Meaning
http.get(url, params) GET with no body
http.post(url, body, params) POST with a body
http.put(url, body, params) / http.patch(...) Replace or modify
http.del(url, body, params) DELETE (delete is a reserved word, so it is del)
http.head(url, params) / http.options(url, body, params) Metadata requests
http.request(method, url, body, params) The general form behind all of them

The params object is where headers, tags, timeouts and similar options live. It is always the last argument.

Sending JSON

k6 does not guess a content type. When you send JSON you stringify the object yourself and set the header:

JavaScript
import http from 'k6/http';

export default function () {
  const payload = JSON.stringify({ name: 'Keyboard', price: 49 });
  const params = { headers: { 'Content-Type': 'application/json' } };
  const res = http.post('https://api.example.test/items', payload, params);
  console.log(res.status, res.json('id'));
}

If you pass a plain JavaScript object as the body instead, k6 encodes it as a form (application/x-www-form-urlencoded). That is handy for login forms but is a classic mistake when the API wants JSON.

Node.js Stand-in: JSON POST and GET against a local server

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Forms, files and other body types

Body you pass What k6 sends
A string Exactly that string
A plain object A URL-encoded form
An ArrayBuffer Raw bytes
An object containing http.file(...) multipart/form-data
JavaScript
import http from 'k6/http';

const logo = open('./logo.png', 'b'); // init stage only, binary mode

export default function () {
  const data = {
    title: 'Quarterly report',
    file: http.file(logo, 'logo.png', 'image/png'),
  };
  http.post('https://api.example.test/upload', data);
}

Notice that open() runs in the init context, once, outside default. Reading files inside the default function is not allowed. Data and shared files covers this in depth.

What a response contains

A response object has the fields you will use constantly:

  • res.status: the numeric status code (0 means the request itself failed, for example a connection refused).
  • res.body: the body as a string (or bytes, depending on responseType).
  • res.headers: response headers.
  • res.json() and res.json('path.to.field'): parse the body or pick a field using a gjson path.
  • res.timings: a breakdown in milliseconds.
  • res.error and res.error_code: set when the transport failed.

The timings object is the heart of load testing, because it shows where time went:

Field Meaning
blocked Waiting for a free connection slot
connecting TCP connect time
tls_handshaking TLS negotiation
sending Sending the request
waiting Time to first byte: the server thinking
receiving Downloading the body
duration sending + waiting + receiving

The waiting field is usually the one that grows first when a server is overloaded. We use these same numbers as built-in metrics in Built-in metrics.

Params: headers, tags, timeouts

JavaScript
const res = http.get('https://api.example.test/search?q=k6', {
  headers: { Accept: 'application/json', 'X-Request-Source': 'load-test' },
  tags: { name: 'SearchEndpoint' },
  timeout: '10s',
  responseType: 'none', // do not keep the body in memory
});

Two options deserve a special mention for large tests:

  • tags.name groups URLs that differ only by an id, such as /items/17 and /items/18. Without it every distinct URL becomes its own time series, which can explode your results. See Tags and groups.
  • responseType: 'none' (or 'text', 'binary') controls memory. Discarding bodies you never read saves a lot of RAM at high load.
Node.js Stand-in: reading timings and discarding bodies

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common mistakes

  1. Forgetting JSON.stringify and sending an object (it becomes a form).
  2. Forgetting the Content-Type header for JSON.
  3. Using raw ids in URLs without a name tag.
  4. Assuming a status of 0 is a server error: it usually means DNS, TLS or connection trouble.
  5. Calling open() inside the default function.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you pass a plain JavaScript object as the body of http.post()?

    A plain object becomes application/x-www-form-urlencoded. For JSON you must call JSON.stringify and set the Content-Type header.
  2. 2. Which timing field is usually the first to grow when a server is overloaded?

    waiting is the time to first byte, i.e. how long the server takes to respond. Overload shows up there first.
  3. 3. Why do you set tags: { name: '...' } on requests to /items/17, /items/18 and so on?

    The name tag replaces the full URL as the label, so many ids do not create thousands of separate series.
  4. 4. What does a response status of 0 usually mean?

    Status 0 means no HTTP response was received, for example a refused connection, DNS failure or timeout. Inspect res.error.

Summary

  • k6/http has one function per verb; params is always the last argument.
  • JSON needs JSON.stringify plus a Content-Type header; objects become forms.
  • Responses expose status, body, headers, json() and a timings breakdown.
  • Use tags.name for dynamic URLs and responseType to save memory.
  • The runnable examples here are Node stand-ins, not k6.

Next: Batches, Cookies and Redirects