0
0
FastAPIframework~5 mins

TestClient basics in FastAPI

Choose your learning style9 modes available
Introduction

TestClient helps you check if your FastAPI app works correctly without running a real server. It makes testing easy and fast.

You want to check if your API endpoints return the right data.
You need to test how your app handles different requests and responses.
You want to automate tests to catch bugs early.
You want to try your API code without starting the server manually.
Syntax
FastAPI
from fastapi.testclient import TestClient

client = TestClient(app)

response = client.get("/some-path")
print(response.status_code)
print(response.json())
You create TestClient by passing your FastAPI app instance.
Use client methods like get(), post(), put() to simulate HTTP requests.
Examples
This example shows how to test a simple GET endpoint that returns a message.
FastAPI
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

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

client = TestClient(app)

response = client.get("/hello")
print(response.status_code)  # 200
print(response.json())       # {'message': 'Hello World'}
Here, we test sending data with a POST request using JSON.
FastAPI
response = client.post("/items", json={"name": "Book", "price": 10})
print(response.status_code)
print(response.json())
Sample Program

This program creates a FastAPI app with a dynamic greeting endpoint. Then it uses TestClient to call the endpoint with the name 'Alice' and prints the status code and JSON response.

FastAPI
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/greet/{name}")
def greet(name: str):
    return {"greeting": f"Hello, {name}!"}

client = TestClient(app)

response = client.get("/greet/Alice")
print(response.status_code)
print(response.json())
OutputSuccess
Important Notes

TestClient runs your app in the same process, so tests are fast.

Always check response status codes and content to ensure your API behaves as expected.

You can test error cases by sending bad data or wrong paths.

Summary

TestClient lets you test FastAPI apps without a real server.

Use it to send HTTP requests and check responses in your tests.

It helps catch bugs early and makes your API reliable.