Status Codes and Error Handling
A server sends a response after processing a request. Requests can fail because input is invalid, a resource cannot be found, or an internal error occurs.
Clients need to understand the failure to respond appropriately. They might ask a user to correct input or display a message that the resource does not exist.
HTTP uses three-digit status codes to describe outcomes. Retrieving a post might return 200 OK, creating one 201 Created, and a missing post 404 Not Found.
Setting a Status Code
Set status_code on a FastAPI decorator to choose the successful response code. FastAPI uses it when the handler returns normally.
Add status_code=201 to the post creation decorator in main.py:
@app.post(
"/posts",
summary="Create a post",
response_model=PostResponse,
status_code=201,
)
200 OK means success; 201 Created specifically means a new resource was created. Since this API creates posts, 201 describes its result more precisely.
FastAPI's status module provides named constants. status.HTTP_201_CREATED is integer 201, but its name makes the meaning clearer in code.
from fastapi import status
@app.post(
"/posts",
summary="Create a post",
response_model=PostResponse,
status_code=status.HTTP_201_CREATED,
)
Without an explicit status_code, a normal successful response defaults to 200 OK.
Handling Errors
When request processing fails, return a suitable error status. FastAPI provides HTTPException for this purpose.
Add error handling to get_post_handler:
from fastapi import HTTPException
@app.get(
"/posts/{post_id}",
summary="Get a post",
response_model=PostResponse,
)
def get_post_handler(post_id: int = Path(ge=1)):
for post in posts:
if post["id"] == post_id:
return post
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Post not found.",
)
HTTPException takes an error code as status_code and a client-facing explanation as detail. If no post matches after checking the entire list, FastAPI returns 404 Not Found with the message in the response body's detail field.
Check Your Understanding
Decide whether each statement is true or false.
- HTTP status codes help clients distinguish success from different categories of failure.
- Omitting the decorator's status code produces a successful response without any status code.
- An HTTP exception's detail can provide a client-facing error explanation.
Answers and Explanations
- True — Clients can use status codes to decide how to handle the result.
- False — Normal successful responses default to
200 OK. - True — The status code identifies the outcome, while
detailsupplies an explanation in the body.