How to Load Test a Local API with Locust in Python
Defines a Locust load test that simulates traffic to local endpoints, enabling manual load testing against a development server.
pip install locust
Python code
18 linesfrom locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(1, 3)
@task
def home_page(self):
self.client.get("/")
@task(3)
def about_page(self):
self.client.get("/about")
if __name__ == "__main__":
print("Run with: locust -f this_file.py --host=http://localhost:8000")
print("Open http://localhost:8080 to start load testing.")
Output
Run with: locust -f this_file.py --host=http://localhost:8000
Open http://localhost:8080 to start load testing.
How it works
The HttpUser class defines a simulated user that hits your local server. The @task decorator marks methods that are executed during the test; the optional weight (like @task(3) for about_page) means that endpoint is hit three times as often as the default weight 1. Setting wait_time = between(1, 3) adds realistic user think time between requests. When you run locust -f this_file.py --host=http://localhost:8000, Locust serves a web UI at localhost:8080 where you can set the number of users and spawn rate, then start the test.
Common mistakes
- Forgetting to include a valid `--host` pointing to your running local server
- Defining tasks without the `@task` decorator so Locust ignores them
- Using a wait_time of 0, which floods the server and gives unrealistic results
Variations
- Run the test headless with `--headless -u 10 -r 2` for a CLI-only load test
- Use `SequentialTaskSet` to enforce an order of operations, like login then view a page
Real-world use cases
- Checking that a locally running FastAPI or Flask dev server handles expected traffic before deploy.
- Simulating spike traffic in a CI pipeline to catch performance regressions early.
- Load testing a staging API to verify scaling capacity before a product launch.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.