0
0
PytestHow-ToBeginner ยท 4 min read

How to Test FastAPI with Pytest: Simple Guide

To test FastAPI with pytest, use FastAPI's TestClient to simulate API requests inside your test functions. Write test cases that call your API endpoints and assert expected responses using pytest assertions.
๐Ÿ“

Syntax

Use TestClient from fastapi.testclient to create a client for your FastAPI app. Then write test functions with pytest that call client methods like .get() or .post(). Use assertions to check response status and data.

  • TestClient(app): creates a test client for your FastAPI app.
  • client.get(path): sends a GET request to the API.
  • assert response.status_code == 200: checks the HTTP status code.
  • assert response.json() == expected_data: checks the JSON response body.
python
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/hello")
def read_hello():
    return {"message": "Hello, world!"}

client = TestClient(app)

def test_read_hello():
    response = client.get("/hello")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello, world!"}
๐Ÿ’ป

Example

This example shows a simple FastAPI app with one GET endpoint and a pytest test function that verifies the endpoint returns the correct message and status code.

python
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/greet/{name}")
def greet(name: str):
    return {"greeting": f"Hello, {name}!"}

client = TestClient(app)

def test_greet():
    response = client.get("/greet/Alice")
    assert response.status_code == 200
    assert response.json() == {"greeting": "Hello, Alice!"}

    response = client.get("/greet/Bob")
    assert response.status_code == 200
    assert response.json() == {"greeting": "Hello, Bob!"}
Output
============================= test session starts ============================= collected 1 item test_app.py . [100%] ============================== 1 passed in 0.05s ==============================
โš ๏ธ

Common Pitfalls

Common mistakes when testing FastAPI with pytest include:

  • Not using TestClient and trying to call app routes directly.
  • Forgetting to assert both status_code and response content.
  • Not handling async endpoints properly (use TestClient which handles async).
  • Using global state in tests causing flaky results.

Always isolate tests and use fresh client instances if needed.

python
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/fail")
async def fail():
    return {"msg": "This is async"}

client = TestClient(app)

def test_fail_wrong():
    # Wrong: calling async function directly without await
    # response = fail()  # This won't work
    pass

def test_fail_right():
    response = client.get("/fail")
    assert response.status_code == 200
    assert response.json() == {"msg": "This is async"}
๐Ÿ“Š

Quick Reference

Remember these tips when testing FastAPI with pytest:

  • Use TestClient to simulate HTTP requests.
  • Test both status codes and response data.
  • Write independent tests to avoid shared state issues.
  • Use descriptive test function names for clarity.
โœ…

Key Takeaways

Use FastAPI's TestClient to simulate API calls in pytest tests.
Always assert both HTTP status codes and response content for accuracy.
Avoid calling async endpoints directly; use TestClient to handle async properly.
Write isolated tests to prevent interference from shared state.
Name test functions clearly to describe what they verify.