Using HTTP Requests in Locust: Basic and Advanced Guide
This tutorial explains how to install Locust, write Python scripts with HttpUser tasks for GET and POST requests, run the tool, configure the web UI, and apply advanced features like custom headers, cookies, and response handling for effective load testing.
Locust is a load testing tool that provides built‑in support for HTTP requests via the HttpUser class, allowing you to simulate many concurrent users.
Basic steps
1. Install Locust with pip install locust .
2. Write a Locust script (locustfile.py). The example defines a WebsiteUser class inheriting from HttpUser with three tasks: index_page (GET “/”), get_posts (GET “/posts”), and create_post (POST “/posts” with JSON data).
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(1, 5) # wait 1‑5 seconds between tasks
@task
def index_page(self):
"""Visit home page"""
self.client.get("/")
@task
def get_posts(self):
"""Get list of posts"""
self.client.get("/posts")
@task
def create_post(self):
"""Create a new post"""
post_data = {
"title": "foo",
"body": "bar",
"userId": 1,
}
headers = {'Content-Type': 'application/json'}
self.client.post("/posts", json=post_data, headers=headers)3. Start Locust with locust -f locustfile.py and open the web UI at http://localhost:8089.
4. In the web UI, set the number of users to simulate and the hatch rate, then click “Start swarming”.
Advanced usage
Beyond basic GET and POST, Locust supports other HTTP methods (PUT, DELETE, etc.) and additional client features.
Use custom headers: self.client.get("/path", headers={"Authorization": "Bearer your_token"}) .
Use cookies: self.client.get("/path", cookies={"session_id": "your_session_id"}) or set global cookies in on_start method.
Handling responses
Capture responses with catch_response=True and mark success or failure based on status code:
with self.client.get("/path", catch_response=True) as response:
if response.status_code == 200:
response.success()
else:
response.failure(f"Failed with status code: {response.status_code}")This guide provides both basic and advanced techniques for using HTTP requests in Locust to build effective performance testing scripts.
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.