Script Valley
FastAPI: Build Production Python APIs
Testing FastAPI ApplicationsLesson 5.3

How to write tests for authenticated FastAPI routes

login flow in tests, Authorization header, Bearer token, pytest fixture for auth token, test user creation, reusable auth fixture, 401 testing

Testing Authenticated Routes

Testing authenticated routes requires obtaining a real or mocked token and including it in the Authorization header of subsequent requests.

Fixture that creates a user and returns a token

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

client = TestClient(app)

@pytest.fixture
def auth_token():
    # Register
    client.post("/register", json={
        "email": "test@test.com",
        "password": "secret123"
    })
    # Login
    response = client.post("/token", data={
        "username": "test@test.com",
        "password": "secret123"
    })
    return response.json()["access_token"]

def test_get_profile(auth_token):
    response = client.get(
        "/me",
        headers={"Authorization": f"Bearer {auth_token}")
    }
    assert response.status_code == 200
    assert response.json()["email"] == "test@test.com"

def test_unauthorized_access():
    response = client.get("/me")
    assert response.status_code == 401

The /token endpoint uses form data, not JSON — use data= not json= in TestClient. Always test both the authenticated success case and the unauthenticated 401 case.

For repeated token use, store the auth_token fixture output in a header dict to avoid repeating the string formatting.

Up next

How to test FastAPI with a real database using pytest fixtures

Sign in to track progress