Testing FastAPI Applications (Pytest + TestClient)

 

 Introduction

Writing APIs is great but how do you ensure they work correctly?That’s where testing comes in.

In this blog, you’ll learn:

  • How to test FastAPI APIs
  • Using pytest
  • Using FastAPI’s TestClient

Why Testing is Important?

Testing helps you:

  • Catch bugs early.
  • Ensure code reliability.
  • Prevent breaking changes.
  • Improve code quality.

Step 1: Install Testing Tools

pip install pytest httpx

Step 2: FastAPI TestClient

FastAPI provides a built-in client for testing APIs.

from fastapi.testclient import TestClient
from app.main import app

client = TestClient(app)

Project Structure for Testing

project/
├── app/
├── tests/
│ ├── test_main.py

Step 3: Write Your First Test

tests/test_main.py

def test_home():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "FastAPI project is running!"}

Step 4: Test POST Request

def test_create_item():
response = client.post("/items/", json={
"name": "Book",
"description": "Education"
})

assert response.status_code == 200
assert response.json()["name"] == "Book"

Step 5: Testing Protected Routes

def test_protected():
token = "your_test_token"

response = client.get(
"/protected",
headers={"Authorization": f"Bearer {token}"}
)

assert response.status_code in [200, 401]

Step 6: Run Tests

pytest

Output:

==== test session starts ====
collected 3 items

test_main.py ...

Using Fixtures (Advanced)

Fixtures help reuse setup code.

import pytest

@pytest.fixture
def sample_data():
return {"name": "Test", "description": "Sample"}

def test_with_fixture(sample_data):
response = client.post("/items/", json=sample_data)
assert response.status_code == 200

Testing Database (Optional)

For DB testing:

  • Use test database
  • Use rollback after tests

Common Mistakes

Not testing edge cases
Using real database instead of test DB
Hardcoding values
Ignoring failed tests

Best Practices

Write tests for all endpoints
Keep tests simple & readable
Use fixtures for reuse
Automate tests (CI/CD)


Key Takeaways

  • FastAPI provides built-in testing tools
  • pytest is simple and powerful
  • Always test APIs before deployment
  • Good tests = reliable applications

Comments

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Middleware & CORS in FastAPI

Python Data Handling