Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 36 ยท Concepts and Scripts

GET and POST Requests in k6

Send your first requests with k6 http.get and http.post, set headers and JSON bodies, read the response object, parse JSON and use batch requests, with a runnable stand-in.

Nearly every k6 test is built from HTTP requests, and the k6/http module keeps them short. Unlike Node.js code, k6 requests are synchronous from your script's point of view: http.get() pauses the iteration and returns the finished response object. There are no promises and no await in a normal script. This lesson shows the everyday request methods and how to read a response. Deeper material (cookies, redirects, auth, multipart uploads) appears in the Protocols and APIs chapter.

http.get

JavaScript
import http from 'k6/http';

export default function () {
  const res = http.get('http://localhost:3000/api/products?limit=10');

  console.log(res.status);                  // 200
  console.log(res.timings.duration);        // total time in ms
  console.log(res.headers['Content-Type']); // header value
  console.log(res.body.length);             // body as a string
}

The response object res has these useful fields:

Field Meaning
res.status HTTP status code (0 if the request failed at network level).
res.body Response body as a string (or ArrayBuffer for binary).
res.headers Object of response headers.
res.timings Object with duration, waiting, sending, receiving, blocked, connecting, tls_handshaking.
res.error Error message if the request failed (empty on success).
res.url Final URL after redirects.
res.json() Parse the body as JSON; pass a selector like res.json('items.0.id').

http.post and request bodies

http.post(url, body, params) takes the body as its second argument. To send JSON, stringify the object and set the content type yourself.

JavaScript
import http from 'k6/http';

export default function () {
  const payload = JSON.stringify({ name: 'Ada', plan: 'pro' });
  const params = { headers: { 'Content-Type': 'application/json' } };

  const res = http.post('http://localhost:3000/api/users', payload, params);
  const user = res.json();
  console.log(`created user ${user.id}`);
}

If you pass a plain object as the body, k6 sends it as a form (application/x-www-form-urlencoded), which is a very common surprise. Stringify when the API wants JSON.

The other verbs follow the same pattern: http.put(url, body, params), http.patch(...), http.del(url, body, params) (note: del, because delete is a keyword), http.head(url, params) and http.options(url, body, params). For anything unusual use the general form http.request(method, url, body, params).

The params object

The last argument of every request is params, an object with options for that one request:

JavaScript
const res = http.get(url, {
  headers: { Authorization: 'Bearer abc', Accept: 'application/json' },
  timeout: '10s',          // fail the request after 10 s
  tags: { endpoint: 'products' }, // custom tag for filtering metrics
  redirects: 3,            // follow at most 3 redirects
  responseType: 'text',    // 'text', 'binary' or 'none'
});

responseType: 'none' discards the body, which saves memory and CPU when you only care about timing. You will tag requests properly in Groups and Tags.

Errors are not exceptions

A 404 or 500 does not throw. The request "succeeds" as far as the JavaScript is concerned and you get a response with res.status 404. If the server cannot be reached at all, k6 also does not throw: you get res.status === 0 and res.error filled in. Either way the failure is recorded in the http_req_failed metric. This is why you must verify responses explicitly with checks, the topic of the next chapter.

Batch requests

http.batch() sends several requests in parallel, like a browser loading a page's resources. It returns an array of responses in the same order.

JavaScript
const responses = http.batch([
  ['GET', 'http://localhost:3000/api/products'],
  ['GET', 'http://localhost:3000/api/categories'],
  { method: 'GET', url: 'http://localhost:3000/api/cart', params: { headers: { Cookie: 'x=1' } } },
]);
console.log(responses.map((r) => r.status));

By default k6 opens up to 6 connections per host in a batch (batchPerHost), which matches typical browsers.

A runnable stand-in

The program below is not k6. It builds a small API server and a tiny helper that mimics http.get and http.post: each call returns an object shaped like the k6 response (status, body, headers, json(), timings). That lets you practise reading responses and see the form-versus-JSON body difference.

Node.js Stand-in: a k6-style response object

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.

Notice that the 404 does not raise an error; your code has to look at the status. In real k6 the same is true, and check() is the tool for it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does http.get() return in a k6 script?

    k6 HTTP calls are synchronous from the script's view and return the response object immediately.
  2. 2. You call http.post(url, { name: 'Ada' }) with a plain object. What body is sent?

    A plain object is sent as application/x-www-form-urlencoded. Use JSON.stringify plus a Content-Type header for JSON.
  3. 3. What happens when the server returns a 500 status?

    HTTP error statuses are normal responses. They are recorded as failures in metrics but do not throw.
  4. 4. Which method name sends an HTTP DELETE request?

    delete is a reserved word in JavaScript, so k6 calls it http.del.

Summary

  • http.get(url, params) and http.post(url, body, params) return the response directly; no promises.
  • Read res.status, res.body, res.headers, res.timings, and res.json().
  • Stringify JSON bodies and set Content-Type; plain-object bodies become forms.
  • Failed responses do not throw; check them explicitly.
  • http.batch() sends requests in parallel; params carries headers, timeouts and tags.

Next: Groups and Tags