How to Set HTTP Request Headers in Locust
This guide explains how to configure custom HTTP request headers in Locust for GET, POST, and shared header scenarios, providing code examples, best practices for security, dynamic updates, and error handling to ensure effective load testing of APIs.
In Locust, configuring HTTP request headers is straightforward by passing a headers dictionary to the client methods.
1. Basic GET request with custom headers
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(1, 5) # set user wait time
@task
def get_with_custom_header(self):
headers = {
'Authorization': 'Bearer your_access_token',
'Content-Type': 'application/json'
}
self.client.get("/api/resource", headers=headers)This example defines a WebsiteUser class that inherits from HttpUser ; the get_with_custom_header task creates a header dictionary with an authorization token and JSON content type, then sends a GET request.
2. POST request with custom headers and JSON payload
@task
def post_with_custom_header(self):
headers = {
'Authorization': 'Bearer your_access_token',
'Content-Type': 'application/json'
}
payload = {
"title": "foo",
"body": "bar",
"userId": 1
}
self.client.post("/api/resource", json=payload, headers=headers)Here the same headers are used for a POST request, and a JSON payload is supplied via the json argument.
3. Sharing headers across multiple requests
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(1, 5)
def on_start(self):
"""Called when a virtual user starts"""
self.headers = {
'Authorization': 'Bearer your_access_token',
'Content-Type': 'application/json'
}
@task
def make_requests(self):
self.client.get("/api/resource1", headers=self.headers)
self.client.post("/api/resource2", json={"key": "value"}, headers=self.headers)By defining self.headers in the on_start method, the same header set can be reused for any subsequent requests, avoiding repetition.
Notes
• Security: Do not hard‑code sensitive information such as API keys; use environment variables or external configuration files.
• Dynamic updates: If header values change during a test, ensure they are refreshed before each request.
• Error handling: Incorporate appropriate error handling to manage network failures or unexpected server responses.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.