- Courses
- 📚Libraries & Frameworks
- ⚡FastAPI
- Foundations of FastAPI
- Pydantic Models
- Error Handling
On this page
Handling Errors in FastAPI
Published on August 9, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
FastAPI produces two distinct kinds of errors, and knowing which one applies to a given failure is what separates clean error handling from code that either fights the framework or leaks more than it should. Validation errors — a malformed request body, a query parameter of the wrong type — are generated automatically by Pydantic before a path operation function ever runs, with no code written for them at all. Business logic errors — an account that doesn't exist, a division by zero, credentials that don't match — happen inside the function itself, after the input has already passed validation, and those require deliberately raising an HTTPException.
Automatic Validation Errors​
FastAPI validates request bodies, query parameters, and path parameters through Pydantic, and returns a 422 Unprocessable Entity response automatically the moment any of them fails to match its declared type — no exception needs to be raised by hand for this category of failure.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Task(BaseModel):
title: str
completed: bool
@app.post("/tasks")
def create_task(task: Task):
return {"message": "Task created", "task": task}
Sending this body:
{
"title": 123,
"completed": "nope"
}
produces:
{
"detail": [
{
"type": "string_type",
"loc": ["body", "title"],
"msg": "Input should be a valid string",
"input": 123
},
{
"type": "bool_parsing",
"loc": ["body", "completed"],
"msg": "Input should be a valid boolean, unable to interpret input",
"input": "nope"
}
]
}
loc identifies exactly which field failed and where it came from (body, here, rather than query or path); msg is a plain-language description of the problem; type is a stable, machine-readable error code that code calling the API can check against directly, without parsing the message text. This response shape is generated the same way for every route in an app, appears automatically in /docs and /redoc as the documented error format, and requires no code in the path operation function itself — by the time create_task would run, a request like this one has already been rejected.
Raising Custom HTTP Exceptions​
A request can be perfectly well-formed — every field the right type — and still represent a failure the application needs to reject, for reasons Pydantic has no way to know about. HTTPException is how a path operation function signals that kind of failure deliberately:
from fastapi import HTTPException
@app.get("/divide")
def divide(x: float, y: float):
if y == 0:
raise HTTPException(status_code=400, detail="Division by zero is not allowed")
return {"result": x / y}
/divide?x=10&y=2 returns {"result": 5.0} normally. /divide?x=10&y=0 passes validation without issue — both x and y are valid floats — but fails for a reason only the function's own logic can catch, and raise HTTPException(...) is what turns that failure into a proper HTTP response: {"detail": "Division by zero is not allowed"} with a 400 status code.
Custom error fields​
status_code accepts any valid HTTP status code — 400 for a bad request, 404 for a missing resource, 403 for a forbidden action, and so on — chosen to match what actually happened rather than defaulting to a generic code for every failure. detail is the message returned to the client, and can also be a structured object rather than a plain string when a client needs more than one piece of information back. An optional headers argument lets specific HTTP headers ride along with the error response — most commonly seen on authentication failures, where a 401 response conventionally includes a WWW-Authenticate header indicating which authentication scheme is expected.
Example: resource not found​
@app.get("/tasks/{task_id}")
def get_task(task_id: int):
fake_db = {1: "Buy milk", 2: "Write code"}
if task_id not in fake_db:
raise HTTPException(status_code=404, detail="Task not found")
return {"task_id": task_id, "title": fake_db[task_id]}
/tasks/1 returns {"task_id": 1, "title": "Buy milk"}. /tasks/99 passes validation — 99 is a valid integer — but fails to exist in fake_db, and the 404 correctly communicates "this resource doesn't exist," which is a meaningfully different situation from 422's "this request wasn't shaped correctly."
Choosing Between Automatic Validation and HTTPException​
The dividing line between the two comes down to when the failure can be detected. If a value's type or structure alone is enough to know it's wrong — a string where a number was expected, a required field left out — that's exactly what Pydantic's automatic validation already handles, and adding manual checks for the same thing inside the function duplicates work the framework already does for free. If a value is well-formed but still invalid for reasons specific to the application's logic — a nonexistent ID, a business rule being violated, a duplicate entry — that's squarely HTTPException territory, since no type hint could have caught it. One consistent habit worth keeping regardless of which mechanism is used: an error message shown to a client should describe what went wrong in terms a client can act on, not surface internal implementation detail — a raw database exception message or a stack trace can reveal table names, query structure, or file paths that have no reason to leave the server, and HTTPException's detail should be written deliberately rather than passed straight through from whatever internal exception was caught.
Customizing the Validation Error Response​
The structure shown earlier for automatic 422 errors is FastAPI's default, but it can be replaced with a custom exception handler when an application needs a different shape — a flatter structure for a specific frontend, for instance:
from fastapi import Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
errors = {".".join(map(str, err["loc"])): err["msg"] for err in exc.errors()}
return JSONResponse(status_code=422, content={"errors": errors})
Registering this handler with @app.exception_handler(RequestValidationError) replaces FastAPI's default validation error response app-wide with whatever shape this function returns — here, a flat {"errors": {"body.title": "Input should be a valid string"}} instead of the nested detail list shown earlier. This is worth reaching for only when a specific error format is genuinely needed elsewhere in the system; the default structure already covers most cases without any extra code.
Practice: Building a Login Endpoint​
class LoginRequest(BaseModel):
username: str
password: str
@app.post("/login")
def login(credentials: LoginRequest):
if credentials.username != "admin" or credentials.password != "secret":
raise HTTPException(status_code=401, detail="Invalid username or password")
return {"message": "Login successful"}
LoginRequest handles the shape of the incoming data — both fields required as strings — through the same automatic validation covered earlier, with no manual checks needed for a missing or non-string field. The credential check itself belongs in the function body, since "these specific values don't match" is exactly the kind of failure only the application's own logic can detect. A request with correct types but wrong credentials — {"username": "admin", "password": "wrong"} — passes validation cleanly and then fails with 401 {"detail": "Invalid username or password"}, while {"username": "admin", "password": "secret"} returns {"message": "Login successful"}. The error message intentionally doesn't specify whether the username or the password was incorrect, since revealing that distinction would let an attacker confirm valid usernames one at a time.
Key Takeaways​
FastAPI's two error mechanisms cover two different moments in a request's lifecycle: automatic 422 validation errors happen before a path operation function ever runs, generated entirely from the types already declared on its parameters, while HTTPException is raised deliberately from inside the function for failures that only the application's own logic can detect. Matching the status code to what actually happened — 404 for missing resources, 401 for failed authentication, 400 for a rejected but well-formed request — keeps error responses informative without exposing internal details a client has no business seeing. The default validation error format can be replaced app-wide with a custom exception handler when a specific shape is genuinely needed, though the built-in structure already covers the majority of cases without any additional code.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Response Models
Next
Building Your First API — Task Manager (Part 1)
-
Automatic Validation Errors
-
Raising Custom HTTP Exceptions
- Custom error fields
- Example: resource not found
-
Choosing Between Automatic Validation and HTTPException
-
Customizing the Validation Error Response
-
Practice: Building a Login Endpoint
-
Key Takeaways
