Testing FastAPI Endpoints

Ethan Cerami
FastAPI Tutorials
Published in
2 min readFeb 28, 2021

Once you understand the basics of FastAPI (see previous posts 1 and 2), the next step is to consider adding automated tests for your API endpoints.

Fortunately, you can do so via pytest and a TestClient class derived from Starlette.

To get started, let’s consider a bare bones API that returns fruit information. Here is the complete code:

Here I have created a fake database with just three fruit, and a single fruit/id endpoint.

Let’s assume that this API is located in the api package, and we run it like so:

uvicorn api.fruit:app — reload

You can then try the endpoint by going to: http://localhost:8000/fruit/1 and verify that you get one apple back.

So far, so good. The next step is to add a test suite. To do so, we create a fastapi.testclient.TestClient object, and then define our tests via the standard pytest conventions. For example, we prefix each test method with test_ and use assert to validate responses from the API.

Here is sample code:

Here we are calling fruit with an ID of 1, and verifying the response with assert. To run the test, just run pytest like so:

pytest

Pytest will automatically collect all your tests and run them sequentially. If all goes well, you should also then see all your tests pass.

You can then easily add additional test cases for error conditions or edge cases.

For example, the following code tests for an invalid identifier:

And, the following code tests for a non-integer identifier:

Hopefully, you can now see how easy it is to add automated tests for your API endpoints. For further information, refer to the official FastAPI tutorial on Testing.

--

--

Ethan Cerami
FastAPI Tutorials

Director, Knowledge Systems Group @ Dana-Farber Cancer Institute, Boston MA.