Get request with headers and query params

Sorry if this question has been asked before but I want to know if there is a simple/easy way to create a get request that accepts headers and query params in 2022?

From the k6 examples we only see an example of query-params without headers. For more context I have a json file with a list of users to login and obtain auth credentials. Then I make a get request but i need to pass in the auth creds and query params because they differ between users.

1 Like

Hi @nazad23, welcome to the community forum :tada: !!

I guess you are referencing URLs with query parameters and HTTP Requests?

While this isn’t explicitly said, there is nothing stopping you combing the two as in:

import { URL } from 'https://jslib.k6.io/url/1.0.0/index.js';
import http from 'k6/http';

export default function () {
    const url = new URL('https://httpbin.test.k6.io/get');

    url.searchParams.append('utm_medium', 'organic');
    url.searchParams.append('utm_source', 'test');
    url.searchParams.append('multiple', ['foo', 'bar']);

    const res = http.get(url.toString(), {headers: {"MyHeader": "value"}});
    console.log(res.body);
    /*
{
  "args": {
    "multiple": "foo,bar",
    "utm_medium": "organic",
    "utm_source": "test"
  },
  "headers": {
    "Host": "httpbin.test.k6.io",
    "Myheader": "value",
    "User-Agent": "k6/0.39.0 (https://k6.io/)",
    "X-Forwarded-Host": "httpbin.test.k6.io",
    "X-Scheme": "http"
  },
  "origin": "77.236.182.19",
  "url": "http://httpbin.test.k6.io/get?utm_medium=organic&utm_source=test&multiple=foo%2Cbar"
}
     */
}

Also, if you will have URLs with multiple query values I would recommend giving them a single name as that will help with aggregation and querying later on.

Hope this helps you!

1 Like