TestClient in FastAPI is a tool used for testing your API by simulating HTTP requests without running a live server. It lets you write and run tests for your endpoints quickly and easily.
Example Code (test.py)
from fastapi.testclient import TestClient
from app.main import app # Just imports the app, doesn't start the server
client = TestClient(app)
def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello, FastAPI"}
Command to run this code: pytest test.py
My actual FastAPI code (main.py) that runs on the server
from fastapi import FastAPI
app = FastAPI()
# Root route
@app.get("/")
def root():
return {"message": "Welcome to the fastAPI"}
Command to run this code: uvicorn main:app --reload
Another Example (test.py) (testing the login endpoint)
from fastapi.testclient import TestClient
from myapp import app # your FastAPI app
client = TestClient(app)
def test_login():
response = client.post(
"/login",
data={"username": "alice", "password": "secret"} # Use 'data' instead of 'json'
)
assert response.status_code == 200
Command to run this code: pytest test.py
Where my actual FastAPI code (main.py) looks like this
@app.post("/login")
def login(form: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
user = get_user_by_username(db, form.username)
if not user or not verify_password(form.password, user.hashed_password):
raise HTTPException(status_code=400, detail="Invalid credentials")
token = create_token({"sub": user.username})
return {"token": token, "token_type": "bearer"}
Command to run this code: uvicorn main:app --reload
Further Reading