FastAPI Error Handling
In API development, error information needs to be returned to the client. FastAPI provides HTTPException to raise HTTP errors, and also supports custom exception handlers to handle more complex error scenarios.
Using HTTPException
When you need to return an error response, raise HTTPException:
Example
from
fastapi
import
FastAPI
,
HTTPException
app
=
FastAPI
(
)
items
=
{
"foo"
:
"The Foo Wrestlers"
,
"bar"
:
"The Bar Fighters"
}
@
app.
get
(
"/items/{item_id}"
)
async
def
read_item
(
item_id:
str
)
:
if
item_id
not
in
items:
When a resource does not exist, raise a 404 error
raise
HTTPException
(
status_code
=
404
,
detail
=
"Item not found"
)
return
{
"item"
: items
[
item_id
]
}
Access the http://127.0.0.1:8000/items/42 , return:
{
"detail": "Item not found"
}
The HTTP status code is 404。
Note that what is used here is
raiseinstead ofreturn。HTTPExceptionis an exception; once raised, FastAPI catches it and returns the corresponding HTTP error response. This is consistent with Python's exception handling mechanism.
HTTPException Parameters
| Parameters | Type | Description |
|---|---|---|
status_code |
int |
HTTP status code (required) |
detail |
Any |
Error detail, which can be a string, dict, list, etc. |
headers |
dict \| None |
Additional response headers (optional) |
Custom Error Details
detail The parameter can be of any type, not limited to strings:
Example
from
fastapi
import
FastAPI
,
HTTPException
app
=
FastAPI
(
)
@
app.
get
(
"/items/{item_id}"
)
async
def
read_item
(
item_id:
str
)
:
if
item_id
==
"invalid"
:
detail can be a dict containing more error information
raise
HTTPException
(
status_code
=
400
,
detail
=
{
"error_code"
:
"INVALID_ID"
,
"message"
:
"Invalid product ID format"
,
"hint"
:
"Please use an alphanumeric ID"
}
)
return
{
"item_id"
: item_id
}
Adding Custom Response Headers
In some scenarios you need to add custom response headers to the error response:
Example
from
fastapi
import
FastAPI
,
HTTPException
app
=
FastAPI
(
)
@
app.
get
(
"/items-header/{item_id}"
)
async
def
read_item_header
(
item_id:
str
)
:
if
item_id
==
"invalid"
:
raise
HTTPException
(
status_code
=
404
,
detail
=
"Item not found"
,
headers
=
{
"X-Error"
:
"There goes my error"
}
,
Custom response header
)
return
{
"item"
: item_id
}
In scenarios where you need to limit the client's request rate (rate limiting), you can add a
Retry-Afterheader to the error response to tell the client when it can retry.
Custom Exception Handlers
You can register handlers for custom exceptions or built-in exceptions to unify the error response format:
Example
from
fastapi
import
FastAPI
,
Request
from
fastapi.
responses
import
JSONResponse
Custom exception class
class
UnicornException
(
Exception
)
:
def
init
(
self
,
name:
str
)
:
self
.
name
=
name
app
=
FastAPI
(
)
Register exception handler
@
app.
exception_handler
(
UnicornException
)
async
def
unicorn_exception_handler
(
request: Request
,
exc: UnicornException
)
:
Return a custom-formatted error response
return
JSONResponse
(
status_code
=
418
,
content
=
{
"message"
: f
"Oops! {exc.name} did something wrong"
}
,
)
@
app.
get
(
"/unicorns/{name}"
)
async
def
read_unicorn
(
name:
str
)
:
if
name
==
"yolo"
:
Raise a custom exception
raise
UnicornException
(
name
=
name
)
return
{
"unicorn_name"
: name
}
Override Default Exception Handlers
FastAPI has default exception handlers that you can override to customize the error response format:
Example
from
fastapi
import
FastAPI
,
Request
from
fastapi.
responses
import
JSONResponse
from
fastapi.
exceptions
import
RequestValidationError
from
starlette.
exceptions
import
HTTPException
as
StarletteHTTPException
app
=
FastAPI
(
)
Override the HTTP exception handler
@
app.
exception_handler
(
StarletteHTTPException
)
async
def
http_exception_handler
(
request: Request
,
exc: StarletteHTTPException
)
:
return
JSONResponse
(
status_code
=
exc.
status_code
,
content
=
{
"error"
: f
"HTTP error: {exc.detail}"
}
,
)
Override the request validation exception handler
@
app.
exception_handler
(
RequestValidationError
)
async
def
validation_exception_handler
(
request: Request
,
exc: RequestValidationError
)
:
return
JSONResponse
(
status_code
=
422
,
content
=
{
"error"
:
"Data validation failed"
,
"details"
: exc.
errors
(
)
}
,
)
RequestValidationErroris the exception raised by FastAPI when request data validation fails. Overriding its handler can customize the response format for validation errors.
Redirection
Use RedirectResponse Implement redirection:
Example
from
fastapi
import
FastAPI
from
fastapi.
responses
import
RedirectResponse
app
=
FastAPI
(
)
@
app.
get
(
"/items/"
)
async
def
read_items
(
)
:
return
{
"items"
:
[
"foo"
,
"bar"
]
}
@
app.
get
(
"/redirect"
)
async
def
redirect
(
)
:
Redirect to /items/
return
RedirectResponse
(
url
=
"/items/"
)
Custom Response Headers and Status Codes
Use JSONResponse Custom response headers and status code:
Example
from
fastapi
import
FastAPI
from
fastapi.
responses
import
JSONResponse
app
=
FastAPI
(
)
@
app.
get
(
"/items/{item_id}"
)
async
def
read_item
(
item_id:
int
)
:
content
=
{
"item_id"
: item_id
}
headers
=
{
"X-Custom-Header"
:
"custom-header-value"
}
return
JSONResponse
(
content
=
content
,
headers
=
headers
)
Summary
- Use
raise HTTPExceptionReturn an HTTP error response detailThe parameter can be of any type (string, dict, list, etc.)- Use
@app.exception_handlerRegister a custom exception handler - You can override FastAPI's default exception handlers to unify the error format
- Use
RedirectResponseImplement redirection