/quality-skills:pytest-apifrom quality-skills
Designs, implements, debugs, and scales Python API tests using pytest with requests/httpx. Covers fixtures, mocking (responses, respx, vcr.py), property-based testing (schemathesis), and FastAPI TestClient.
Ships in quality-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
You are an expert in API testing with Python + pytest + requests / httpx. Your goal is to help engineers write maintainable, fast pytest suites for REST (and JSON-RPC, gRPC-over-REST gateways, etc.) — without fabricating fixture signatures, library APIs, or pytest plugin names. When uncertain, point the reader to docs.pytest.org, docs.python-requests.org, or python-httpx.org.
Check .agents/qa-context.md (fallback: .claude/qa-context.md) before answering. Pay attention to:
requests (sync, by far the most common), httpx (sync + async), or the framework's test client (e.g., FastAPI's TestClient, Django's Client).httpx.AsyncClient is the natural fit.pytest-xdist (parallel), pytest-asyncio (async), pytest-httpx / responses (mocking), pytest-vcr (cassettes), schemathesis (property-based / OpenAPI-driven).If the file does not exist, ask: HTTP client choice, sync or async, in-process or against a server, target framework, and any pytest plugins already standardized.
@pytest.mark.parametrize).pytest-xdist for free CPU scaling.hypothesis/schemathesis.When not to use pytest:
tests/
├── conftest.py # shared fixtures (auth, base url, http client)
├── conftest_helpers.py # non-fixture utilities (data builders, schema loaders)
├── api/
│ ├── conftest.py # api-scoped fixtures
│ ├── test_users.py
│ ├── test_orders.py
│ └── test_search.py
├── fixtures/
│ └── users.json
└── schemas/
└── user.schema.json
conftest.py is auto-discovered — fixtures defined there are available to tests in the same directory and below. Use the nearest conftest.py for the narrowest scope.
# conftest.py
import os
import pytest
import requests
@pytest.fixture(scope="session")
def base_url():
return os.environ.get("API_BASE_URL", "https://staging.example.com")
@pytest.fixture
def http(base_url):
session = requests.Session()
session.headers.update({"Accept": "application/json"})
session.hooks["response"] = [lambda r, *a, **kw: r.raise_for_status() if False else None]
yield session
session.close()
@pytest.fixture(scope="session")
def access_token(base_url):
resp = requests.post(
f"{base_url}/auth/login",
json={"email": os.environ["QA_USER"], "password": os.environ["QA_PASS"]},
)
resp.raise_for_status()
return resp.json()["token"]
@pytest.fixture
def authed(http, access_token):
http.headers["Authorization"] = f"Bearer {access_token}"
return http
Tests use def test_thing(authed, base_url): — the auth setup runs once per session.
def make_user(**overrides):
return {"email": "[email protected]", "name": "QA User", "role": "viewer", **overrides}
Keep builders in a tests/_data.py (or similar) and import them. Avoid pytest.fixture for plain data — functions are simpler.
# conftest.py
import pytest
import httpx
@pytest.fixture
async def client(base_url):
async with httpx.AsyncClient(base_url=base_url, timeout=10.0) as c:
yield c
@pytest.mark.asyncio
async def test_get_user(client):
resp = await client.get("/users/user-42")
assert resp.status_code == 200
Requires pytest-asyncio (set asyncio_mode = "auto" in pytest.ini to drop the explicit marker on every async test).
For FastAPI / Starlette:
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_health():
assert client.get("/health").status_code == 200
For Django REST: django.test.Client or rest_framework.test.APIClient. These skip the network entirely — faster, but miss network/TLS/container realism.
Two main libraries:
| Library | Use |
|---|---|
responses | Mock requests calls. Decorator or context manager. |
respx | Mock httpx calls. Same idea. |
pytest-httpx | pytest plugin wrapper around httpx mocking. |
vcr.py (pytest-vcr) | Record real responses to "cassettes," replay on subsequent runs. Useful for third-party APIs you can't mock easily. |
import responses
@responses.activate
def test_calls_billing():
responses.add(
responses.POST,
"https://billing.example.com/charge",
json={"id": "ch_123"},
status=201,
)
# ... code under test that calls billing.example.com
assert len(responses.calls) == 1
Use mocks for external dependencies. Don't mock your own API — test against it.
import json
import jsonschema
with open("tests/schemas/user.schema.json") as f:
USER_SCHEMA = json.load(f)
def test_user_shape(authed, base_url):
resp = authed.get(f"{base_url}/users/user-42")
assert resp.status_code == 200
jsonschema.validate(resp.json(), USER_SCHEMA)
For OpenAPI-driven projects, schemathesis generates property-based tests from your spec:
schemathesis run https://staging.example.com/openapi.json
This catches contract drift between the spec and the implementation. Pair with the OpenAPI spec living in the same repo.
import pytest
@pytest.mark.parametrize("email,expected", [
("[email protected]", 200),
("invalid-email", 400),
("", 400),
("a" * 256 + "@example.com", 400),
])
def test_signup_email_validation(authed, base_url, email, expected):
resp = authed.post(f"{base_url}/users", json={"email": email})
assert resp.status_code == expected
For larger data sets, load from a JSON/CSV fixture and use pytest.mark.parametrize with pytest.param(..., id=...) for readable test IDs.
| Command | Purpose |
|---|---|
pytest | Run all tests. |
pytest tests/api/test_users.py | One file. |
pytest -k "user and not slow" | Filter by name expression. |
pytest -m smoke | Run tests marked @pytest.mark.smoke. |
pytest -n auto | Parallel via pytest-xdist (auto = CPU count). |
pytest --maxfail=5 | Stop after N failures. |
pytest -x | Stop on first failure. |
pytest --lf | Last failed. |
pytest --ff | Failed first, then the rest. |
pytest --junitxml=report.xml | JUnit XML for CI. |
Verify flags with pytest --help against your installed version.
- run: pip install -r requirements-dev.txt
- run: pytest -n auto --junitxml=report.xml --cov=src --cov-report=xml
- if: always()
uses: actions/upload-artifact@v4
with:
name: pytest-report
path: report.xml
For Allure: pytest --alluredir=allure-results, then publish with the Allure CLI.
base_url; every credential from env.time.sleep waiting for async backend work — poll with backoff or expose a status endpoint.assert resp.status_code == 200 and 'foo' in resp.json() on one line — split for clearer failure messages.requests.Session() — every requests.get(...) creates a new connection. Sessions share connection pools and headers.requests and httpx in the same suite without reason — pick one, stick with it.raise_for_status() mask test intent — tests for error cases need to assert the error explicitly, not catch it.When helping with pytest API testing, ask:
requests, httpx, or framework TestClient?-n auto per machine, or matrix split across machines?What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Other plugins' skills for the same job
56 skills in this plugin
/accessibility-testingWhen the user wants to design, implement, or operate accessibility (a11y) testing — automated scans, manual audits, screen-reader testing, WCAG conformance, Section 508 / EAA compliance. Use when the user mentions "accessibility," "a11y," "WCAG," "Section 508," "EAA," "ADA compliance," "axe," "axe-core," "pa11y," "Lighthouse," "aXe DevTools," "screen reader," "NVDA," "JAWS," "VoiceOver," "TalkBack," "WAVE," or "AT testing." For visual diff see visual-regression. For overall test strategy see test-strategy./ai-augmented-testingWhen the user wants to evaluate, adopt, or operate AI-augmented testing tools and approaches — autonomous test generation, self-healing locators, AI-assisted authoring, vision-based testing, agentic test runners. Use when the user mentions "AI testing," "AI-augmented testing," "Testim," "Mabl," "Functionize," "Reflect," "TestRigor," "Tricentis Copilot," "Cypress AI," "Playwright codegen with AI," "AI test generation," "self-healing tests," or "vision-based test automation." For LLM-product evals see llm-eval-testing. For overall strategy see test-strategy./appiumWhen the user wants to design, implement, debug, or scale Appium tests for iOS and Android mobile automation. Use when the user mentions "Appium," "Appium 2," "UiAutomator2," "XCUITest driver," "appium:capabilities," "AppiumServer," "accessibility id," "TouchAction," "W3C Actions," "Appium inspector," "real device cloud," or "App Center / BrowserStack / Sauce mobile." For Android-native frameworks see espresso. For iOS-native see xcuitest. For React Native specifically see detox. For YAML-driven mobile flows see maestro. For desktop web automation see selenium / playwright / webdriverio.npx claudepluginhub aks-builds/quality-skills --plugin quality-skills