
FastAPI
FastAPI provides HTTPException for returning HTTP errors with proper status codes and messages. It's the standard way to signal client errors in your API.
HTTPException raises an error that FastAPI automatically converts to an HTTP response:
from fastapi import FastAPI, HTTPException
from fastapi import status
app = FastAPI()
@app.get("/items/{item_id}")
async def get_item(item_id: int):
if item_id == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found"
)
return {"item_id": item_id}# 400 Bad Request - Invalid input
raise HTTPException(status_code=400, detail="Invalid input data")
# 401 Unauthorized - Authentication required
raise HTTPException(status_code=401, detail="Not authenticated")
# 403 Forbidden - No permission
raise HTTPException(status_code=403, detail="No access to this resource")
# 404 Not Found - Resource doesn't exist
raise HTTPException(status_code=404, detail="Resource not found")
# 409 Conflict - Resource conflict
raise HTTPException(status_code=409, detail="Resource already exists")from fastapi import status
@app.get("/users/{user_id}")
async def get_user(user_id: int):
if user_id < 0:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="User ID must be positive",
headers={"X-Error-Code": "INVALID_USER_ID"}
)
return {"user_id": user_id}@app.get("/secure")
async def secure_endpoint(token: str = None):
if not token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
headers={"WWW-Authenticate": "Bearer"}
)
return {"message": "authenticated"}In production APIs, HTTPException is used for:
Example: E-commerce API
@app.post("/orders/")
async def create_order(order: Order, current_user: User):
if not current_user.is_verified:
raise HTTPException(
status_code=403,
detail="Email must be verified to place orders"
)
if order.total < 0:
raise HTTPException(
status_code=400,
detail="Order total cannot be negative"
)
return {"order_id": 123, "status": "created"}Resources
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