Testing helps verify that your FastAPI application works correctly.
FastAPI provides TestClient, which can be used to send requests to your API and check the responses.
Using TestClient
First, import TestClient:
from fastapi.testclient import TestClient
Create a test client using your FastAPI application:
client = TestClient(app)
Writing a Test
Suppose your FastAPI application has a home endpoint that returns:
{
"message": "Hello FastAPI"
}
You can test it with:
from fastapi.testclient import TestClient
client = TestClient(app)
def test_home():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello FastAPI"
}
Understanding the Code
Import TestClient
from fastapi.testclient import TestClient
TestClient allows you to make HTTP requests to your FastAPI application during testing.
Create the Test Client
client = TestClient(app)
The TestClient uses your FastAPI application to execute test requests.
Create a Test Function
def test_home():
Pytest recognizes functions beginning with test_ as test functions.
Send a GET Request
response = client.get("/")
This sends a GET request to the / endpoint.
The response is stored in the response variable.
Check the Status Code
assert response.status_code == 200
This verifies that the API returned HTTP status code 200.
If the status code is different, the test fails.
Check the Response Data
assert response.json() == {
"message": "Hello FastAPI"
}
This verifies that the API returned the expected JSON response.
Running Tests
Install pytest if it is not already installed:
pip install pytest
Then run:
pytest
Test Output
A successful test produces output similar to:
========================
1 passed
========================
Testing Flow
The basic testing flow is:
Test Function
↓
TestClient
↓
FastAPI Endpoint
↓
Response
↓
Assertions
↓
Test Passed / Failed
Why Test APIs?
Testing helps ensure that:
- Endpoints return the correct status codes.
- API responses contain the expected data.
- Changes to the application do not unexpectedly break existing functionality.
- API behavior can be verified automatically.
Summary
In this topic, we learned:
- FastAPI provides
TestClientfor testing APIs. client.get()can be used to test GET endpoints.assertis used to verify expected results.response.status_codechecks the HTTP status code.response.json()checks the returned JSON data.pytestcan be used to run FastAPI tests.