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.

Medium Python 3.9+ Aug 9, 2026 Testing & modern typing 16 views 0 copies

Requires third-party packages — install first
pip install locust

Python code

18 lines
Python 3.9+
from 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

stdout
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

  1. Run the test headless with `--headless -u 10 -r 2` for a CLI-only load test
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Testing & modern typing

Related tutorials and quizzes for this topic.