0
0
FastapiHow-ToBeginner · 3 min read

How to Use TestClient in FastAPI for API Testing

Use TestClient from fastapi.testclient to simulate HTTP requests to your FastAPI app in tests. Instantiate it with your app, then call methods like .get() or .post() to test endpoints synchronously.
📐

Syntax

The TestClient is created by passing your FastAPI app instance. You then use HTTP methods like .get(), .post(), .put(), etc., on the client to simulate requests.

Each method returns a response object with attributes like .status_code and .json() to check the result.

python
from fastapi.testclient import TestClient
from fastapi import FastAPI

app = FastAPI()

client = TestClient(app)

response = client.get("/some-endpoint")
print(response.status_code)
print(response.json())
💻

Example

This example shows a simple FastAPI app with one GET endpoint. We use TestClient to call the endpoint and check the response status and JSON content.

python
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/hello")
def read_hello():
    return {"message": "Hello, FastAPI!"}

client = TestClient(app)

def test_read_hello():
    response = client.get("/hello")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello, FastAPI!"}

# Run the test function
if __name__ == "__main__":
    test_read_hello()
    print("Test passed!")
Output
Test passed!
⚠️

Common Pitfalls

  • Not importing TestClient from fastapi.testclient: Using other test clients may not work as expected.
  • Forgetting to pass the FastAPI app instance: You must pass your app to TestClient to test it.
  • Trying to use async calls with TestClient: TestClient methods are synchronous; do not use await with them.
  • Not checking response status before accessing JSON: Always check response.status_code to avoid errors.
python
from fastapi.testclient import TestClient
from fastapi import FastAPI

app = FastAPI()

client = TestClient(app)

# Wrong: Using async with TestClient
# async def test_wrong():
#     response = await client.get("/hello")  # This will cause error

# Right:
def test_right():
    response = client.get("/hello")
    assert response.status_code == 200
📊

Quick Reference

Here is a quick summary of TestClient usage:

ActionCode ExampleDescription
Create clientclient = TestClient(app)Initialize TestClient with your FastAPI app
Send GET requestresponse = client.get("/path")Simulate a GET request to an endpoint
Check statusresponse.status_codeGet HTTP status code of the response
Get JSON dataresponse.json()Parse response body as JSON
Send POST requestresponse = client.post("/path", json={})Send POST with JSON payload

Key Takeaways

Use TestClient from fastapi.testclient to test FastAPI apps synchronously.
Instantiate TestClient with your FastAPI app instance before making requests.
Call HTTP methods like .get() or .post() on the client to simulate requests.
Always check response.status_code before accessing response content.
Do not use async/await with TestClient methods; they are synchronous.