Skip to main content

Example Async FastAPI App (main.py)

from fastapi import FastAPI, HTTPException

app = FastAPI()

fake_db = {"alice": "Engineer", "bob": "Designer"}

@app.get("/users/{username}")
async def get_user(username: str):
if username not in fake_db:
raise HTTPException(status_code=404, detail="User not found")
return {"username": username, "job": fake_db[username]}

@app.post("/users")
async def create_user(username: str, job: str):
if username in fake_db:
raise HTTPException(status_code=400, detail="User already exists")
fake_db[username] = job
return {"message": "User created", "username": username}

Requirements

Install async test tools:

pip install pytest pytest-asyncio httpx[http2] fastapi

Async Tests (test_main_async.py)

Use an async test client from httpx.AsyncClient.

import pytest
from httpx import AsyncClient
from main import app

1. Test GET async endpoint

@pytest.mark.asyncio
async def test_get_existing_user():
async with AsyncClient(app=app, base_url="http://test") as client:
response = await client.get("/users/alice")

assert response.status_code == 200
data = response.json()
assert data["username"] == "alice"
assert data["job"] == "Engineer"

2. Test GET missing user

@pytest.mark.asyncio
async def test_get_missing_user():
async with AsyncClient(app=app, base_url="http://test") as client:
response = await client.get("/users/unknown")

assert response.status_code == 404
assert response.json() == {"detail": "User not found"}

3. Test POST async endpoint

@pytest.mark.asyncio
async def test_create_new_user():
async with AsyncClient(app=app, base_url="http://test") as client:
response = await client.post(
"/users", params={"username": "charlie", "job": "Manager"}
)

assert response.status_code == 200
assert response.json()["message"] == "User created"
assert response.json()["username"] == "charlie"

4. Test POST existing user

@pytest.mark.asyncio
async def test_create_existing_user():
async with AsyncClient(app=app, base_url="http://test") as client:
response = await client.post(
"/users", params={"username": "alice", "job": "Engineer"}
)

assert response.status_code == 400
assert response.json() == {"detail": "User already exists"}

Run tests

pytest -v