
FastAPI
Client error codes indicate that the request was invalid or couldn't be processed. They range from 400-499.
The request is malformed or invalid.
from fastapi import HTTPException
@app.get("/items")
async def list_items(limit: int):
if limit < 1:
raise HTTPException(status_code=400, detail="limit must be at least 1")
return {"items": []}Authentication is required but not provided.
from fastapi.security import HTTPBearer
security = HTTPBearer()
@app.get("/protected")
async def protected_route(credentials = Depends(security)):
if not credentials:
raise HTTPException(status_code=401, detail="Not authenticated")
return {"data": "secret"}Authenticated, but not allowed to access.
@app.delete("/admin/users/{user_id}")
async def delete_user(user_id: int, current_user = Depends(get_current_user)):
if current_user.role != "admin":
raise HTTPException(status_code=403, detail="Not authorized")
return {"deleted": True}Resource doesn't exist.
@app.get("/users/{user_id}")
async def get_user(user_id: int):
user = db.get_user(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return userRequest is valid but contains semantic errors.
# FastAPI automatically returns 422 for:
# - Type validation errors
# - Missing required fields
# - Invalid format
@app.post("/users")
async def create_user(name: str, age: int):
# POST {"name": "John", "age": "invalid"} → 422
# POST {"name": "John"} → 422 (age required)
return {"id": 1, "name": name, "age": age}| Code | Meaning | Example |
|---|---|---|
| 400 | Bad Request | Invalid query parameters |
| 401 | Unauthorized | Missing API key |
| 403 | Forbidden | No permission |
| 404 | Not Found | Resource doesn't exist |
| 422 | Unprocessable Entity | Invalid field types |
from fastapi import HTTPException, status
@app.get("/items/{item_id}")
async def get_item(item_id: int):
item = db.get_item(item_id)
if not item:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found"
)
return itemResources
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