YouTip LogoYouTip

Fastapi Testing

FastAPI applications can be tested using the TestClient provided by Starlette. TestClient is based on the requests library, allowing you to test FastAPI applications without starting an actual HTTP server.

Install Dependencies

First, make sure you have installed the necessary testing dependencies:

pip install httpx pytest

Create a FastAPI Application

Suppose we have a simple FastAPI application, the code is as follows:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_main():
    return {"msg": "Hello World"}

Write Test Code

Next, we use TestClient to write test code for this application:

from fastapi.testclient import TestClient

from .main import app

client = TestClient(app)

def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": "Hello World"}

Run Tests

Use the pytest command to run the tests:

pytest

If all assertions pass, it means your FastAPI application is working properly.

More Examples

Here is a more complete example, including testing for POST requests and exception handling:

from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
    if item_id == 0:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id, "q": q}

@app.post("/items/")
async def create_item(item_id: int, name: str):
    return {"item_id": item_id, "name": name}

client = TestClient(app)

def test_read_item():
    response = client.get("/items/1?q=foo")
    assert response.status_code == 200
    assert response.json() == {"item_id": 1, "q": "foo"}

def test_read_item_not_found():
    response = client.get("/items/0")
    assert response.status_code == 404
    assert response.json() == {"detail": "Item not found"}

def test_create_item():
    response = client.post("/items/", json={"item_id": 2, "name": "Bar"})
    assert response.status_code == 200
    assert response.json() == {"item_id": 2, "name": "Bar"}

In this example, we test three different scenarios:

  • GET request returns a successful response.
  • GET request returns a 404 error.
  • POST request successfully creates an item.

Using TestClient and pytest, you can easily write and run various tests for FastAPI applications.

← Flutter TutorialFastapi Static Files β†’