2 Hours

7. HTTP Status Codes & Error Handling

Error Handling

HTTP status codes are three-digit numbers that tell the client what happened to their request. Using the correct status codes is essential for building intuitive, standards-compliant APIs. FastAPI provides built-in tools for raising HTTP exceptions with the right status codes. To test these examples, save to main.py and run uvicorn main:app --reload.

Understanding HTTP Status Code Categories

Status codes are grouped into five categories. Each category tells a different story about the request outcome.

  • 1xx (Informational): Request received, continuing process. Rarely used in REST APIs.
  • 2xx (Success): The request was successfully received, understood, and accepted.
  • 3xx (Redirection): Further action is needed to complete the request. Used for moved resources.
  • 4xx (Client Error): The request contains bad syntax or cannot be fulfilled. The client made a mistake.
  • 5xx (Server Error): The server failed to fulfill a valid request. Your server has a problem.

The Most Common Status Codes

200 OK (success), 201 Created (resource created), 204 No Content (success with no response), 400 Bad Request (client error), 401 Unauthorized (not logged in), 403 Forbidden (not allowed), 404 Not Found (resource missing), 422 Unprocessable Entity (validation failed), 500 Internal Server Error (server crashed).

2xx Success Codes in Detail

Python 3
from fastapi import FastAPI, status

app = FastAPI()

# 200 OK - Standard success for GET, PUT, PATCH
@app.get("/users/{user_id}", status_code=status.HTTP_200_OK)
def get_user(user_id: int):
    return {"id": user_id, "name": "Alice"}

# 201 Created - Resource successfully created
@app.post("/users", status_code=status.HTTP_201_CREATED)
def create_user(name: str):
    return {"id": 1, "name": name}

# 204 No Content - Success but no response body (common for DELETE)
@app.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_user(user_id: int):
    return None

# 202 Accepted - Request accepted but processing async
@app.post("/jobs", status_code=status.HTTP_202_ACCEPTED)
def create_job(task: str):
    return {"job_id": "abc123", "status": "processing"}

Raising HTTP Exceptions

When something goes wrong, use HTTPException to return an error response with the appropriate status code and message.

Python 3
from fastapi import FastAPI, HTTPException, status

app = FastAPI()

fake_db = {1: {"name": "Alice"}, 2: {"name": "Bob"}}

@app.get("/users/{user_id}")
def get_user(user_id: int):
    if user_id not in fake_db:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"User with id {user_id} not found"
        )
    return fake_db[user_id]

@app.post("/users")
def create_user(name: str, age: int):
    if age < 18:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="User must be 18 or older"
        )
    return {"id": 3, "name": name, "age": age}
Local Testing: Visit /users/999 to see the 404 error. Try creating a user with age 16 to see the 400 error.

Custom Exception Details with Headers

Python 3
from fastapi import FastAPI, HTTPException, status

app = FastAPI()

@app.get("/protected-data")
def get_protected_data(api_key: str):
    if api_key != "secret123":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid API key",
            headers={"WWW-Authenticate": "Bearer"}
        )
    return {"data": "sensitive information"}

@app.get("/items/{item_id}")
def get_item(item_id: int):
    if item_id > 1000:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail={
                "error": "Invalid ID",
                "message": f"Item ID {item_id} exceeds maximum allowed (1000)",
                "max_allowed": 1000
            }
        )
    return {"item_id": item_id}

4xx Client Error Codes

Python 3
# 400 Bad Request - Malformed syntax
@app.post("/process")
def process(data: dict):
    if "required_field" not in data:
        raise HTTPException(400, detail="Missing required_field")

# 401 Unauthorized - Not authenticated
@app.get("/profile")
def get_profile(token: str):
    if not is_valid_token(token):
        raise HTTPException(401, detail="Invalid or missing token")

# 403 Forbidden - Authenticated but not authorized
@app.delete("/admin/users/{user_id}")
def admin_delete(user_id: int, current_user: dict):
    if current_user["role"] != "admin":
        raise HTTPException(403, detail="Admin privileges required")

# 404 Not Found - Resource doesn't exist
@app.get("/products/{product_id}")
def get_product(product_id: int):
    product = find_product(product_id)
    if not product:
        raise HTTPException(404, detail=f"Product {product_id} not found")

# 409 Conflict - Resource already exists
@app.post("/users")
def create_user(email: str):
    if email_exists(email):
        raise HTTPException(409, detail="Email already registered")

# 422 Unprocessable Entity - Validation failed
@app.post("/orders")
def create_order(quantity: int):
    if quantity < 1:
        raise HTTPException(422, detail="Quantity must be at least 1")

# 429 Too Many Requests - Rate limit exceeded
@app.get("/api/data")
def get_data(request_id: str):
    if rate_limit_exceeded(request_id):
        raise HTTPException(429, detail="Too many requests. Try again later.")

5xx Server Error Codes

Server errors should generally be handled by global exception handlers, not raised manually. They indicate something wrong with your server, not the client's request.

Python 3
from fastapi import FastAPI, HTTPException, status
import logging

logger = logging.getLogger(__name__)

@app.get("/database-data")
async def get_db_data():
    try:
        result = await database_query()
        return result
    except DatabaseConnectionError as e:
        logger.error(f"Database connection failed: {e}")
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Database service unavailable. Please try again later."
        )
    except Exception as e:
        logger.exception(f"Unexpected error: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="An unexpected error occurred"
        )
Local Testing: To see these errors in action, create endpoints that trigger each condition and test them via the /docs interface.

Knowledge Check

Ready to test your understanding of 7. HTTP Status Codes & Error Handling?

Back