Testing

Warning

The current page still doesn’t have a translation for this language.

But you can help translating it: Contributing.

Thanks to Starlette, testing FastAPI applications is easy and enjoyable.

It is based on HTTPX, which in turn is designed based on Requests, so it’s very familiar and intuitive.

With it, you can use pytest directly with FastAPI.

Using TestClient

Info

To use TestClient, first install httpx.

E.g. pip install httpx.

Import TestClient.

Create a TestClient by passing your FastAPI application to it.

Create functions with a name that starts with test_ (this is standard pytest conventions).

Use the TestClient object the same way as you do with httpx.

Write simple assert statements with the standard Python expressions that you need to check (again, standard pytest).

  1. from fastapi import FastAPI
  2. from fastapi.testclient import TestClient
  3. app = FastAPI()
  4. @app.get("/")
  5. async def read_main():
  6. return {"msg": "Hello World"}
  7. client = TestClient(app)
  8. def test_read_main():
  9. response = client.get("/")
  10. assert response.status_code == 200
  11. assert response.json() == {"msg": "Hello World"}

Tip

Notice that the testing functions are normal def, not async def.

And the calls to the client are also normal calls, not using await.

This allows you to use pytest directly without complications.

Technical Details

You could also use from starlette.testclient import TestClient.

FastAPI provides the same starlette.testclient as fastapi.testclient just as a convenience for you, the developer. But it comes directly from Starlette.

Tip

If you want to call async functions in your tests apart from sending requests to your FastAPI application (e.g. asynchronous database functions), have a look at the Async Tests in the advanced tutorial.

Separating tests

In a real application, you probably would have your tests in a different file.

And your FastAPI application might also be composed of several files/modules, etc.

FastAPI app file

Let’s say you have a file structure as described in Bigger Applications:

  1. .
  2. ├── app
  3. ├── __init__.py
  4. └── main.py

In the file main.py you have your FastAPI app:

  1. from fastapi import FastAPI
  2. app = FastAPI()
  3. @app.get("/")
  4. async def read_main():
  5. return {"msg": "Hello World"}

Testing file

Then you could have a file test_main.py with your tests. It could live on the same Python package (the same directory with a __init__.py file):

  1. .
  2. ├── app
  3. ├── __init__.py
  4. ├── main.py
  5. └── test_main.py

Because this file is in the same package, you can use relative imports to import the object app from the main module (main.py):

  1. from fastapi.testclient import TestClient
  2. from .main import app
  3. client = TestClient(app)
  4. def test_read_main():
  5. response = client.get("/")
  6. assert response.status_code == 200
  7. assert response.json() == {"msg": "Hello World"}

…and have the code for the tests just like before.

Testing: extended example

Now let’s extend this example and add more details to see how to test different parts.

Extended FastAPI app file

Let’s continue with the same file structure as before:

  1. .
  2. ├── app
  3. ├── __init__.py
  4. ├── main.py
  5. └── test_main.py

Let’s say that now the file main.py with your FastAPI app has some other path operations.

It has a GET operation that could return an error.

It has a POST operation that could return several errors.

Both path operations require an X-Token header.

Python 3.9+Python 3.6+Python 3.10+ non-AnnotatedPython 3.6+ non-Annotated

  1. from typing import Annotated
  2. from fastapi import FastAPI, Header, HTTPException
  3. from pydantic import BaseModel
  4. fake_secret_token = "coneofsilence"
  5. fake_db = {
  6. "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
  7. "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
  8. }
  9. app = FastAPI()
  10. class Item(BaseModel):
  11. id: str
  12. title: str
  13. description: str | None = None
  14. @app.get("/items/{item_id}", response_model=Item)
  15. async def read_main(item_id: str, x_token: Annotated[str, Header()]):
  16. if x_token != fake_secret_token:
  17. raise HTTPException(status_code=400, detail="Invalid X-Token header")
  18. if item_id not in fake_db:
  19. raise HTTPException(status_code=404, detail="Item not found")
  20. return fake_db[item_id]
  21. @app.post("/items/", response_model=Item)
  22. async def create_item(item: Item, x_token: Annotated[str, Header()]):
  23. if x_token != fake_secret_token:
  24. raise HTTPException(status_code=400, detail="Invalid X-Token header")
  25. if item.id in fake_db:
  26. raise HTTPException(status_code=400, detail="Item already exists")
  27. fake_db[item.id] = item
  28. return item
  1. from typing import Annotated, Union
  2. from fastapi import FastAPI, Header, HTTPException
  3. from pydantic import BaseModel
  4. fake_secret_token = "coneofsilence"
  5. fake_db = {
  6. "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
  7. "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
  8. }
  9. app = FastAPI()
  10. class Item(BaseModel):
  11. id: str
  12. title: str
  13. description: Union[str, None] = None
  14. @app.get("/items/{item_id}", response_model=Item)
  15. async def read_main(item_id: str, x_token: Annotated[str, Header()]):
  16. if x_token != fake_secret_token:
  17. raise HTTPException(status_code=400, detail="Invalid X-Token header")
  18. if item_id not in fake_db:
  19. raise HTTPException(status_code=404, detail="Item not found")
  20. return fake_db[item_id]
  21. @app.post("/items/", response_model=Item)
  22. async def create_item(item: Item, x_token: Annotated[str, Header()]):
  23. if x_token != fake_secret_token:
  24. raise HTTPException(status_code=400, detail="Invalid X-Token header")
  25. if item.id in fake_db:
  26. raise HTTPException(status_code=400, detail="Item already exists")
  27. fake_db[item.id] = item
  28. return item
  1. from typing import Union
  2. from fastapi import FastAPI, Header, HTTPException
  3. from pydantic import BaseModel
  4. from typing_extensions import Annotated
  5. fake_secret_token = "coneofsilence"
  6. fake_db = {
  7. "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
  8. "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
  9. }
  10. app = FastAPI()
  11. class Item(BaseModel):
  12. id: str
  13. title: str
  14. description: Union[str, None] = None
  15. @app.get("/items/{item_id}", response_model=Item)
  16. async def read_main(item_id: str, x_token: Annotated[str, Header()]):
  17. if x_token != fake_secret_token:
  18. raise HTTPException(status_code=400, detail="Invalid X-Token header")
  19. if item_id not in fake_db:
  20. raise HTTPException(status_code=404, detail="Item not found")
  21. return fake_db[item_id]
  22. @app.post("/items/", response_model=Item)
  23. async def create_item(item: Item, x_token: Annotated[str, Header()]):
  24. if x_token != fake_secret_token:
  25. raise HTTPException(status_code=400, detail="Invalid X-Token header")
  26. if item.id in fake_db:
  27. raise HTTPException(status_code=400, detail="Item already exists")
  28. fake_db[item.id] = item
  29. return item

Tip

Prefer to use the Annotated version if possible.

  1. from fastapi import FastAPI, Header, HTTPException
  2. from pydantic import BaseModel
  3. fake_secret_token = "coneofsilence"
  4. fake_db = {
  5. "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
  6. "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
  7. }
  8. app = FastAPI()
  9. class Item(BaseModel):
  10. id: str
  11. title: str
  12. description: str | None = None
  13. @app.get("/items/{item_id}", response_model=Item)
  14. async def read_main(item_id: str, x_token: str = Header()):
  15. if x_token != fake_secret_token:
  16. raise HTTPException(status_code=400, detail="Invalid X-Token header")
  17. if item_id not in fake_db:
  18. raise HTTPException(status_code=404, detail="Item not found")
  19. return fake_db[item_id]
  20. @app.post("/items/", response_model=Item)
  21. async def create_item(item: Item, x_token: str = Header()):
  22. if x_token != fake_secret_token:
  23. raise HTTPException(status_code=400, detail="Invalid X-Token header")
  24. if item.id in fake_db:
  25. raise HTTPException(status_code=400, detail="Item already exists")
  26. fake_db[item.id] = item
  27. return item

Tip

Prefer to use the Annotated version if possible.

  1. from typing import Union
  2. from fastapi import FastAPI, Header, HTTPException
  3. from pydantic import BaseModel
  4. fake_secret_token = "coneofsilence"
  5. fake_db = {
  6. "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
  7. "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
  8. }
  9. app = FastAPI()
  10. class Item(BaseModel):
  11. id: str
  12. title: str
  13. description: Union[str, None] = None
  14. @app.get("/items/{item_id}", response_model=Item)
  15. async def read_main(item_id: str, x_token: str = Header()):
  16. if x_token != fake_secret_token:
  17. raise HTTPException(status_code=400, detail="Invalid X-Token header")
  18. if item_id not in fake_db:
  19. raise HTTPException(status_code=404, detail="Item not found")
  20. return fake_db[item_id]
  21. @app.post("/items/", response_model=Item)
  22. async def create_item(item: Item, x_token: str = Header()):
  23. if x_token != fake_secret_token:
  24. raise HTTPException(status_code=400, detail="Invalid X-Token header")
  25. if item.id in fake_db:
  26. raise HTTPException(status_code=400, detail="Item already exists")
  27. fake_db[item.id] = item
  28. return item

Extended testing file

You could then update test_main.py with the extended tests:

  1. from fastapi.testclient import TestClient
  2. from .main import app
  3. client = TestClient(app)
  4. def test_read_item():
  5. response = client.get("/items/foo", headers={"X-Token": "coneofsilence"})
  6. assert response.status_code == 200
  7. assert response.json() == {
  8. "id": "foo",
  9. "title": "Foo",
  10. "description": "There goes my hero",
  11. }
  12. def test_read_item_bad_token():
  13. response = client.get("/items/foo", headers={"X-Token": "hailhydra"})
  14. assert response.status_code == 400
  15. assert response.json() == {"detail": "Invalid X-Token header"}
  16. def test_read_inexistent_item():
  17. response = client.get("/items/baz", headers={"X-Token": "coneofsilence"})
  18. assert response.status_code == 404
  19. assert response.json() == {"detail": "Item not found"}
  20. def test_create_item():
  21. response = client.post(
  22. "/items/",
  23. headers={"X-Token": "coneofsilence"},
  24. json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"},
  25. )
  26. assert response.status_code == 200
  27. assert response.json() == {
  28. "id": "foobar",
  29. "title": "Foo Bar",
  30. "description": "The Foo Barters",
  31. }
  32. def test_create_item_bad_token():
  33. response = client.post(
  34. "/items/",
  35. headers={"X-Token": "hailhydra"},
  36. json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"},
  37. )
  38. assert response.status_code == 400
  39. assert response.json() == {"detail": "Invalid X-Token header"}
  40. def test_create_existing_item():
  41. response = client.post(
  42. "/items/",
  43. headers={"X-Token": "coneofsilence"},
  44. json={
  45. "id": "foo",
  46. "title": "The Foo ID Stealers",
  47. "description": "There goes my stealer",
  48. },
  49. )
  50. assert response.status_code == 400
  51. assert response.json() == {"detail": "Item already exists"}

Whenever you need the client to pass information in the request and you don’t know how to, you can search (Google) how to do it in httpx, or even how to do it with requests, as HTTPX’s design is based on Requests’ design.

Then you just do the same in your tests.

E.g.:

  • To pass a path or query parameter, add it to the URL itself.
  • To pass a JSON body, pass a Python object (e.g. a dict) to the parameter json.
  • If you need to send Form Data instead of JSON, use the data parameter instead.
  • To pass headers, use a dict in the headers parameter.
  • For cookies, a dict in the cookies parameter.

For more information about how to pass data to the backend (using httpx or the TestClient) check the HTTPX documentation.

Info

Note that the TestClient receives data that can be converted to JSON, not Pydantic models.

If you have a Pydantic model in your test and you want to send its data to the application during testing, you can use the jsonable_encoder described in JSON Compatible Encoder.

Run it

After that, you just need to install pytest:

Testing - 图1

It will detect the files and tests automatically, execute them, and report the results back to you.

Run the tests with:

Testing - 图2