Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
FastAPI Cookbook

You're reading from   FastAPI Cookbook Develop high-performance APIs and web applications with Python

Arrow left icon
Product type Paperback
Published in Aug 2024
Publisher Packt
ISBN-13 9781805127857
Length 358 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Giunio De Luca Giunio De Luca
Author Profile Icon Giunio De Luca
Giunio De Luca
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Chapter 1: First Steps with FastAPI 2. Chapter 2: Working with Data FREE CHAPTER 3. Chapter 3: Building RESTful APIs with FastAPI 4. Chapter 4: Authentication and Authorization 5. Chapter 5: Testing and Debugging FastAPI Applications 6. Chapter 6: Integrating FastAPI with SQL Databases 7. Chapter 7: Integrating FastAPI with NoSQL Databases 8. Chapter 8: Advanced Features and Best Practices 9. Chapter 9: Working with WebSocket 10. Chapter 10: Integrating FastAPI with other Python Libraries 11. Chapter 11: Middleware and Webhooks 12. Chapter 12: Deploying and Managing FastAPI Applications 13. Index 14. Other Books You May Enjoy

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:

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime