Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying FastAPI Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
FastAPI Cookbook

FastAPI Cookbook

By : Giunio De Luca
4.3 (4)
close
close
FastAPI Cookbook

FastAPI Cookbook

4.3 (4)
By: Giunio De Luca

Overview of this book

FastAPI is a cutting-edge Python framework that is revolutionizing the way web apps and APIs are built. Known for its speed, simplicity, and scalability, FastAPI empowers developers to create high-performing applications with ease. This book will help you leverage FastAPI’s immense potential to handle high-traffic scenarios and integrate seamlessly with modern Python tools. The book begins by familiarizing you with the basics of setting up and configuring your FastAPI environment before moving to the intricacies of building RESTful APIs, managing data with SQL and NoSQL databases, and handling authentication and authorization. Next, you'll focus on advanced topics such as custom middleware, WebSocket communication, and integration with various Python libraries. Each chapter is meticulously crafted with practical recipes, progressing from foundational concepts to advanced features and best practices. The concluding chapters show you how to optimize performance, implement rate limiting, and execute background tasks, empowering you to become a proficient FastAPI developer. By the end of this book, you'll have gained the skills you need to migrate existing apps to FastAPI, and be equipped to tackle any challenge in the modern web development landscape, ensuring your apps are not only functional, but also efficient, secure, and scalable.
Table of Contents (15 chapters)
close
close

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:

Create a Note

Modal Close icon
You need to login to use this feature.
notes
bookmark search playlist download font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Delete Note

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Edit Note

Modal Close icon
Write a note (max 255 characters)
Cancel
Update Note

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY