AUTOMATION FRAMEWORKS

Pytest Fixtures for API Testing: Beyond the Basics

Most people meet pytest fixtures as a neat way to create a requests.Session and pass it into tests. That's a fine start, but fixtures do much more for an API suite than that. They decide what state each test shares, how test data gets created, and whether cleanup actually happens when a test fails halfway through.

They've also become more important now that GitHub Copilot and coding agents write a lot of test code. An assistant writing a new test will reuse the fixtures it can see. If your fixtures are well scoped and clearly named, generated tests come out consistent. If they're tangled, or missing, the assistant invents its own setup inline and you end up with twenty slightly different ways of creating a user.

In this article I'll go through the patterns I rely on beyond the basics: getting scope right, factory fixtures for dynamic data, teardown that runs, parametrised fixtures, and using fixtures to inject a fake model client when the code under test calls an LLM.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

Get scope and isolation right first

Fixture scope controls how often a fixture runs and therefore what tests share. The rule I use for API suites:

  • Session scope for things that are expensive and read-only: configuration, the base URL, an authenticated client whose token outlives the run.
  • Module or class scope rarely. It's tempting for "create this once for these tests", but it couples tests to each other.
  • Function scope (the default) for anything a test creates or changes on the server.
import os

import pytest
import requests


@pytest.fixture(scope="session")
def api_base_url():
    return os.environ.get("API_BASE_URL", "http://localhost:8000")


@pytest.fixture(scope="session")
def api_session():
    session = requests.Session()
    session.headers["Authorization"] = f"Bearer {os.environ['API_TOKEN']}"
    yield session
    session.close()

Pytest also enforces a useful constraint: a fixture can only depend on fixtures of the same or wider scope. A session fixture can't use a function fixture. If you hit that error, it's usually telling you that something you thought was shared really belongs to one test.

When the suite runs in parallel with pytest-xdist, remember that session scope means once per worker process, not once per run. Anything a session fixture creates on the server gets created once per worker.

Factory fixtures for dynamic test data

A fixture that returns one fixed user is fine until a test needs two users, or a user with a specific role. A factory fixture returns a function instead, and tracks what it created so it can clean up:

import uuid

import pytest


@pytest.fixture
def make_user(api_session, api_base_url):
    created = []

    def _make_user(role="member", **overrides):
        payload = {
            "email": f"qa-{uuid.uuid4().hex[:10]}@example.test",
            "role": role,
            **overrides,
        }
        response = api_session.post(f"{api_base_url}/users", json=payload, timeout=10)
        assert response.status_code == 201, response.text
        user = response.json()
        created.append(user["id"])
        return user

    yield _make_user

    for user_id in reversed(created):
        api_session.delete(f"{api_base_url}/users/{user_id}", timeout=10)


def test_admin_can_deactivate_member(make_user, api_session, api_base_url):
    member = make_user()
    admin = make_user(role="admin")
    ...

The test reads as intent ("a member and an admin") and the data is unique per call, which keeps parallel runs safe. Cleanup runs in reverse order, which matters when later resources depend on earlier ones.

Teardown that runs when the test fails

Code after yield in a fixture runs when the test finishes, whether it passed or failed. That's what makes yield fixtures the right place for cleanup, rather than cleanup lines at the end of a test body that never execute once an assertion fails.

The subtle part: if the fixture itself raises before reaching yield, its teardown doesn't run. So keep setup minimal before the yield, and in factories, record each resource the moment it's created, as above. If a fixture creates several things in sequence, request.addfinalizer lets you register cleanup for each step as soon as it succeeds. I go deeper on this in structuring API test teardown so it actually runs.

Parametrised fixtures for cross-cutting variations

When every test in a module should run against several variations, such as each user role, parametrise the fixture rather than each test:

import pytest


@pytest.fixture(params=["member", "admin", "auditor"])
def role_user(request, make_user):
    return make_user(role=request.param)


def test_profile_endpoint_returns_own_profile(role_user, api_session, api_base_url):
    response = api_session.get(f"{api_base_url}/users/{role_user['id']}", timeout=10)
    assert response.status_code == 200

Each test that uses role_user runs three times, with the role in the test id. That's often cleaner than repeating @pytest.mark.parametrize on every test.

Fixtures as the vocabulary your AI assistant uses

Here's what I've noticed with AI-assisted test writing: fixtures are the vocabulary an assistant writes in. When I ask Copilot or an agent for a new test, it looks at conftest.py and nearby tests and reaches for what's there. A clear make_user factory means the generated test uses it. No factory means a generated test that posts directly to /users, with a hard-coded email and no cleanup.

So I treat the fixture set as part of the instructions I give an agent. A short section in .github/copilot-instructions.md, or your agent's equivalent file, saves a lot of review:

## Test fixtures
- Create server-side data only through factory fixtures in tests/conftest.py
  (make_user, make_order). Never POST setup data inline in a test.
- Do not add new session-scoped fixtures that create server data.
- If a needed factory doesn't exist, add it to conftest.py with cleanup,
  and mention it in the PR description.

Fixtures also make code that calls a language model testable. If your service takes a model client as a dependency, a fixture can inject a fake that returns canned responses, so the deterministic logic around the model, such as parsing, validation and error handling, gets fast, repeatable tests:

import pytest


class FakeModel:
    def __init__(self, replies):
        self.replies = list(replies)
        self.prompts = []

    def generate(self, prompt):
        self.prompts.append(prompt)
        return self.replies.pop(0)


@pytest.fixture
def fake_model():
    return FakeModel(['{"category": "billing"}'])


def test_ticket_classifier_parses_model_reply(fake_model):
    from app.classifier import classify_ticket
    assert classify_ticket("I was charged twice", model=fake_model) == "billing"
    assert "charged twice" in fake_model.prompts[0]

That test says nothing about whether the real model classifies well; that's a separate evaluation run many times against a labelled set. But it pins down your code's behaviour, including what happens when the model returns malformed output, without network calls or randomness.

Keep conftest.py readable

As fixtures grow, conftest files can turn into a junk drawer, and an assistant will add to the junk drawer just as happily as a person. Keep shared fixtures in the top-level conftest, put area-specific ones in a conftest next to those tests, and give fixtures names that say what they return. My notes on conftest files that don't become a mess cover the layout.

Fixtures are where an API suite's design really lives. Get scope, factories and teardown right, and both your own tests and the ones an assistant writes come out cleaner. If you want to build a suite like this from scratch with Python, VS Code and GitHub Copilot, my API testing courses walk through it.