📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials API Design API Testing

API Testing

5 min read Quiz at the end
Test APIs with pytest+httpx — status codes, response bodies, validation errors, auth, and rate limits.

API Testing

import httpx, pytest

@pytest.fixture
def client():
    with httpx.Client(base_url="http://localhost:8000") as c:
        yield c

def test_get_user(client):
    resp = client.get("/api/users/1")
    assert resp.status_code == 200
    assert resp.json()["id"] == 1

def test_validation(client):
    resp = client.post("/api/users", json={"name":""})
    assert resp.status_code == 422

def test_unauthorized(client):
    resp = client.get("/api/profile")
    assert resp.status_code == 401

def test_rate_limit(client):
    for _ in range(101):
        resp = client.get("/api/search?q=test")
    assert resp.status_code == 429