0
0
FastapiHow-ToBeginner · 3 min read

How to Use HTTPException in FastAPI: Simple Guide

In FastAPI, use HTTPException to return HTTP error responses by raising it with a status code and optional detail message. Import it from fastapi and raise it inside your path operation functions to signal errors like 404 or 400.
📐

Syntax

The HTTPException class is used to raise HTTP errors in FastAPI. You create it by specifying a status_code (like 404 for Not Found) and an optional detail message to explain the error.

Example parts:

  • status_code: HTTP status number (e.g., 404, 400, 500)
  • detail: A string or dict explaining the error
python
from fastapi import HTTPException

raise HTTPException(status_code=404, detail="Item not found")
💻

Example

This example shows a FastAPI app with a path that raises HTTPException if an item is not found in a fake database. It returns a 404 error with a message.

python
from fastapi import FastAPI, HTTPException

app = FastAPI()

fake_items_db = {"foo": "The Foo item", "bar": "The Bar item"}

@app.get("/items/{item_id}")
async def read_item(item_id: str):
    if item_id not in fake_items_db:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id, "description": fake_items_db[item_id]}
Output
GET /items/foo -> 200 OK with JSON {"item_id": "foo", "description": "The Foo item"} GET /items/baz -> 404 Not Found with JSON {"detail": "Item not found"}
⚠️

Common Pitfalls

Common mistakes when using HTTPException include:

  • Not importing HTTPException from fastapi.
  • Raising HTTPException outside of path operation functions where it won't be handled properly.
  • Using incorrect or unsupported HTTP status codes.
  • Not providing a detail message, which can make debugging harder.

Always raise HTTPException inside your route functions and use valid status codes.

python
from fastapi import FastAPI

app = FastAPI()

# Wrong: missing import and raising outside route
# raise HTTPException(status_code=400, detail="Bad request")

# Right:
from fastapi import HTTPException

@app.get("/wrong")
async def wrong():
    raise HTTPException(status_code=400, detail="Bad request")
📊

Quick Reference

ParameterDescriptionExample
status_codeHTTP status code to return404, 400, 500
detailError message or info"Item not found"
headersOptional HTTP headers as dict{"X-Error": "There goes my error"}

Key Takeaways

Use HTTPException to return HTTP errors with status codes and messages in FastAPI.
Always import HTTPException from fastapi and raise it inside your route functions.
Provide a clear detail message to help clients understand the error.
Use valid HTTP status codes to follow web standards.
Avoid raising HTTPException outside of request handlers to ensure proper error handling.