Use TestClient (based on httpx) with pytest to call endpoints without running a server, assert status codes and JSON, and cover success, validation errors and auth failures.
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_create_and_read_item():
r = client.post("/items", json={"name": "pen", "price": 2.5})
assert r.status_code == 201
item_id = r.json()["id"]
assert client.get(f"/items/{item_id}").json()["name"] == "pen"
def test_validation_error():
r = client.post("/items", json={"name": "pen"}) # price missing
assert r.status_code == 422For async tests use httpx.AsyncClient with ASGITransport and pytest-asyncio or the anyio plugin.