Handling errors and exceptions
Error handling is an essential aspect of developing robust and reliable web applications. In FastAPI, managing errors and exceptions is not just about catching unexpected issues but also about proactively designing your application to respond to various error scenarios gracefully.
This recipe will guide you through custom error handling, validating data and handling exceptions, and testing these scenarios to ensure your FastAPI applications are resilient and user-friendly.
How to do it…
FastAPI provides built-in support for handling exceptions and errors.
When an error occurs, FastAPI returns a JSON response containing details about the error, which is very useful for debugging. However, there are situations where you might want to customize these error responses for better user experience or security.
Let’s create a custom error handler that catches a specific type of error and returns a custom response. For instance, if a requested resource is not found, you might want to return a more friendly error message.
To do it, in the main.py
file, add the following code accordingly:
from fastapi import FastAPI, HTTPException from starlette.responses import JSONResponse @app.exception_handler(HTTPException) async def http_exception_handler(request, exc): return JSONResponse( status_code=exc.status_code, content={ "message": "Oops! Something went wrong" }, )
In this example, the http_exception_handler
function will be used to handle HTTPException
errors. Whenever an HTTPException
error is raised anywhere in your application, FastAPI will use this handler to return a custom response.
You can test the response by creating a new endpoint that raises an HTTP exception:
@app.get("/error_endpoint") async def raise_exception(): raise HTTPException(status_code=400)
The endpoint will explicitly throw the HTTP error response to showcase the customized message defined in the previous step.
Now, spin the server from the command line with the following command:
$ uvicorn main:app
Open the browser at http://localhost:8000/error_endpoint
, and you will have a JSON response like this:
{ "message": "Oops! Something went wrong" }
The response returns the default message we defined for any HTTP exception returned by the code.
There’s more…
As discussed in the previous recipe, Defining and using request and response models, FastAPI uses Pydantic models for data validation. When a request is made with data that does not conform to the defined model, FastAPI automatically raises an exception and returns an error response.
In some cases, you might want to customize the response for validation errors. FastAPI makes this quite straightforward:
import json from fastapi import Request, status from fastapi.exceptions import RequestValidationError from fastapi.responses import PlainTextResponse @app.exception_handler(RequestValidationError) async def validation_exception_handler( request: Request, exc: RequestValidationError ): return PlainTextResponse( "This is a plain text response:" f" \n{json.dumps(exc.errors(), indent=2)}", status_code=status.HTTP_400_BAD_REQUEST, )
This custom handler will catch any RequestValidationError
error and return a plain text response with the details of the error.
If you try, for example, to call the POST /book
endpoint with a number type of title
instead of a string, you will get a response with a status code of 400
and body:
This is a plain text response: [ { "type": "string_type", "loc": [ "body", "author" ], "msg": "Input should be a valid string", "input": 3, "url": "https://errors.pydantic.dev/2.5/v/string_type" }, { "type": "greater_than", "loc": [ "body", "year" ], "msg": "Input should be greater than 1900", "input": 0, "ctx": { "gt": 1900 }, "url": "https://errors.pydantic.dev/2.5/v/greater_than" } ]
You can also, for example, mask the message to add a layer of security to protect from unwanted users using it incorrectly.
This is all you need to customize responses when a request validation error occurs.
You will use this basic knowledge as you move to the next chapter. Chapter 2 will teach you more about data management in web applications, showing you how to set up and use SQL and NoSQL databases and stressing data security. This will not only improve your technical skills but also increase your awareness of creating scalable and reliable FastAPI applications.
See also
You can find more information about customizing errors and exceptions using FastAPI in the official documentation:
- Handling Errors: https://fastapi.tiangolo.com/tutorial/handling-errors/