
FastAPI
Testing ensures your API works correctly. FastAPI makes it easy with the TestClient.
Install pytest:
pip install pytest httpxCreate `test_main.py`:
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}Run tests:
pytestfrom fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_get_item():
response = client.get("/items/1")
assert response.status_code == 200
assert response.json()["id"] == 1
def test_create_item():
response = client.post("/items", json={"name": "Test", "price": 10.0})
assert response.status_code == 201
assert response.json()["name"] == "Test"def test_not_found():
response = client.get("/items/999")
assert response.status_code == 404
def test_bad_request():
response = client.post("/items", json={"price": "invalid"})
assert response.status_code == 422def test_create_user():
response = client.post("/users", json={
"name": "John",
"email": "john@example.com"
})
assert response.status_code == 201
assert response.json()["name"] == "John"# Run all tests
pytest
# Run specific file
pytest test_main.py
# Run with verbose output
pytest -v
# Run specific test
pytest test_main.py::test_read_rootResources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep โข Build Real โข Verify Skills โข Launch Forward