Skip to main content

Status Codes and Error Handling in Web APIs

Following our lesson on Request and Response Bodies: Pydantic models, this article focuses on Status Codes and Error Handling in Web APIs. Returning appropriate HTTP status codes and handling errors gracefully is crucial for building a robust and predictable API.


📚 Prerequisites

  • A running FastAPI application.
  • Understanding of Pydantic models.

🎯 Article Outline: What You'll Master

  • HTTP Status Codes: Understanding the meaning of common status codes.
  • Returning Status Codes: How to return different status codes in FastAPI.
  • Handling Errors: Using HTTPException to handle errors.
  • Custom Exception Handlers: Creating custom handlers for your own exceptions.

🧠 Section 1: The Core Concepts of HTTP Status Codes

HTTP status codes are a standard way for a server to tell a client the outcome of a request. Some common codes are:

  • 200 OK: The request was successful.
  • 201 Created: The request was successful and a resource was created.
  • 204 No Content: The request was successful but there is no representation to return.
  • 400 Bad Request: The server could not understand the request due to invalid syntax.
  • 401 Unauthorized: The client must authenticate itself to get the requested response.
  • 403 Forbidden: The client does not have access rights to the content.
  • 404 Not Found: The server can not find the requested resource.
  • 500 Internal Server Error: The server has encountered a situation it doesn't know how to handle.

💻 Section 2: Deep Dive - Implementation and Walkthrough

Let's see how to work with status codes and errors in FastAPI.

# main.py
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel

class Item(BaseModel):
name: str
price: float

app = FastAPI()

items = {"foo": {"name": "Foo", "price": 50.2}}

@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: str):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return items[item_id]

@app.put("/items/{item_id}", response_model=Item)
async def update_item(item_id: str, item: Item):
if item_id not in items:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found",
headers={"X-Error": "There goes my error"},
)
items[item_id] = item
return item

Step-by-Step Code Breakdown:

  1. raise HTTPException(...): When an item is not found, we raise an HTTPException. FastAPI will catch this exception and return the specified status_code and detail message to the client.
  2. status_code=status.HTTP_404_NOT_FOUND: You can use the status module for convenience instead of memorizing the numbers.
  3. headers: You can also add custom headers to your error response.

💡 Conclusion & Key Takeaways

You've learned how to use HTTP status codes and handle errors in your FastAPI application. This is a critical part of creating a well-behaved and developer-friendly API.

Let's summarize the key takeaways:

  • Use standard HTTP status codes to indicate the outcome of a request.
  • Use HTTPException to handle errors and return appropriate error responses.
  • You can create custom exception handlers for more advanced error handling scenarios.

➡️ Next Steps

In the next article, "Dependency Injection in FastAPI", we will explore one of FastAPI's most powerful features for managing dependencies and reusing code.


Glossary

  • HTTP Status Code: A code that indicates the outcome of an HTTP request.
  • HTTPException: A FastAPI exception class for returning HTTP error responses.

Further Reading