0
0
FastapiHow-ToBeginner · 4 min read

How to Test FastAPI Applications Using pytest

To test FastAPI apps with pytest, use FastAPI's TestClient to simulate HTTP requests to your API endpoints. Write test functions with pytest that call your app through TestClient and assert expected responses.
📐

Syntax

Use TestClient from fastapi.testclient to create a client for your FastAPI app. Write test functions with pytest that call HTTP methods like get, post on this client. Assert the response status and data to verify behavior.

python
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello World"}

client = TestClient(app)

def test_read_root():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello World"}
💻

Example

This example shows a simple FastAPI app with one GET endpoint. The test uses TestClient to call the endpoint and checks that the response status is 200 and the JSON matches the expected message.

python
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id, "name": "Item Name"}

client = TestClient(app)

def test_read_item():
    response = client.get("/items/42")
    assert response.status_code == 200
    assert response.json() == {"item_id": 42, "name": "Item Name"}
Output
PASSED
⚠️

Common Pitfalls

  • Not using TestClient and trying to call FastAPI routes directly without a client.
  • Forgetting to assert both status_code and response content.
  • Not importing TestClient from fastapi.testclient.
  • Running tests without the pytest command or missing the test_ prefix on test functions.
python
from fastapi import FastAPI

app = FastAPI()

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

# Wrong: calling route function directly
# response = wrong_test()
# assert response == {"msg": "This is wrong"}  # This skips HTTP layer

# Right way:
from fastapi.testclient import TestClient
client = TestClient(app)

def test_right():
    response = client.get("/wrong")
    assert response.status_code == 200
    assert response.json() == {"msg": "This is wrong"}
📊

Quick Reference

Remember these key points when testing FastAPI with pytest:

  • Use TestClient(app) to simulate requests.
  • Write test functions starting with test_.
  • Use client.get(), client.post(), etc. to call endpoints.
  • Assert response.status_code and response.json() for correctness.
  • Run tests with the pytest command in your terminal.

Key Takeaways

Use FastAPI's TestClient to simulate HTTP requests in pytest tests.
Always assert both response status code and JSON content for accuracy.
Prefix test functions with test_ so pytest can discover them.
Avoid calling route functions directly; test through HTTP client instead.
Run tests using the pytest command to execute your test suite.