Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
FastAPI Cookbook
FastAPI Cookbook

FastAPI Cookbook: Develop high-performance APIs and web applications with Python

Arrow left icon
Profile Icon Giunio De Luca
Arrow right icon
€12.99 €26.99
Book Aug 2024 358 pages 1st Edition
eBook
€12.99 €26.99
Print
€22.99 €33.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Giunio De Luca
Arrow right icon
€12.99 €26.99
Book Aug 2024 358 pages 1st Edition
eBook
€12.99 €26.99
Print
€22.99 €33.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€12.99 €26.99
Print
€22.99 €33.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon AI Assistant (beta) to help accelerate your learning
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

FastAPI Cookbook

First Steps with FastAPI

Welcome to the exciting world of FastAPI, a modern, high-performance framework for building APIs and web applications in Python. This first chapter is your gateway to understanding and harnessing the power of FastAPI. Here, you’ll take your initial steps into setting up your development environment, creating your very first FastAPI project, and exploring its fundamental concepts.

FastAPI stands out for its speed, ease of use, and comprehensive documentation, making it a preferred choice for developers looking to build scalable and efficient web applications. In this chapter, you’ll practically engage in setting up FastAPI, learning how to navigate its architecture, and understanding its core components. You’ll gain hands-on experience by defining simple API endpoints, handling HTTP methods, and learning about request and response handling. These foundational skills are crucial for any developer stepping into the world of modern web development with FastAPI.

By the end of this chapter, you will have a solid understanding of FastAPI’s basic structure and capabilities. You’ll be able to set up a new project, define API endpoints, and have a grasp on handling data with FastAPI. This knowledge sets the stage for more advanced topics and complex applications you’ll encounter as you progress through the book.

In this chapter, we’re going to cover the following recipes:

  • Setting up your development environment
  • Creating a new FastAPI project
  • Understanding FastAPI basics
  • Defining your first API endpoint
  • Working with path and query parameters
  • Defining and using request and response models
  • Handling errors and exceptions

Each recipe is designed to provide you with practical knowledge and direct experience, ensuring that by the end of this chapter, you’ll be well equipped to start building your own FastAPI applications.

Technical requirements

To embark on your journey with FastAPI, you’ll need to set up an environment that supports Python development and FastAPI’s functionalities. Here’s a list of the technical requirements and installations needed for this chapter:

  • Python: FastAPI is built on Python, so you’ll need a Python version compatible with your FastAPI version. You can download the latest version of it from python.org.
  • FastAPI: Install FastAPI using pip, Python’s package manager. You can do it by running pip install fastapi from the command terminal.
  • Uvicorn: FastAPI requires an Asynchronous Server Gateway Interface (ASGI) server, and Uvicorn is a lightning-fast ASGI server implementation. Install it using pip install uvicorn.
  • Integrated development environment (IDE): An IDE such as Visual Studio Code (VS Code), PyCharm, or any other IDE that supports Python development will be necessary for writing and testing your code.
  • Postman or Swagger UI: For testing API endpoints. FastAPI automatically generates and hosts Swagger UI, so you can use it right out of the box.
  • Git: Version control is essential, and Git is a widely used system. If not already installed, you can get it from git-scm.com.
  • GitHub account: A GitHub account is required to access the code repositories. Sign up at github.com if you haven’t already.

The code used in the chapter is available on GitHub at the following address: https://github.com/PacktPublishing/FastAPI-Cookbook/tree/main/Chapter01. You can clone or download the repository at https://github.com/PacktPublishing/FastAPI-Cookbook to follow along on your local machine.

Setting up your development environment

This recipe, dedicated to setting up your development environment, is a critical foundation for any successful project in web development. Here, you’ll learn how to install and configure all the essential tools needed to start building with FastAPI.

We begin by guiding you through the installation of Python, the core language behind FastAPI. Next, we’ll move on to installing FastAPI itself, along with Uvicorn, a lightning-fast ASGI server, which serves as the bedrock for running your FastAPI applications.

Setting up an IDE is our next stop. Whether you prefer VS Code, PyCharm, or any other Python-friendly IDE, we’ll provide tips to make your development process smoother and more efficient.

Lastly, we’ll introduce you to Git and GitHub – indispensable tools for version control and collaboration in modern software development. Understanding how to use these tools will not only help you manage your code effectively but also open doors to the vast world of community-driven development and resources.

Getting ready

FastAPI works with Python, so you need to check your Python version before using it. This is an important step for setting up FastAPI. We will guide you through how to install it.

Windows installation

If you work on Windows, follow these steps to install Python:

  1. Visit the official Python website: python.org.
  2. Download the latest version of Python or any other version higher than 3.9.
  3. Run the installer. Ensure to check the box that says Add Python to PATH before clicking Install Now.
  4. After the installation, open Command Prompt and type python --version to confirm the installation.

macOS/Linux installation

macOS usually comes with Python pre-installed; however, it might not be the latest version.

You can use Homebrew (a package manager for macOS). To install it, open the terminal and run it:

$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/\Homebrew/install/HEAD/install.sh)"

Then, you can install Python – still from the terminal – with the following command:

$ brew install python

On Linux, you can install Python using the package manager by running the following command:

$ sudo apt-get install python3

That’s all you need to install Python on macOS and Linux systems.

Checking the installation

You can then check that Python is correctly installed by running the following command in the terminal:

$ python --version

If you installed it on Linux, the binary command is python3, so you can check that Python is correctly installed by running the following command:

$ python3 --version

Once Python is installed, we want to make sure that the Python’s package manager is correctly installed. It comes with Python’s installation, and it’s called pip.

From a terminal window, run the following command:

$ pip --version

On Linux, run the following command:

$ pip3 --version

Once Python is installed on your computer, you can now consider installing FastAPI.

How to do it...

When you have Python and pip ready, we can continue with installing FastAPI, the IDE. Then, we will configure Git.

We will do it by following these steps:

  1. Installing FastAPI and Uvicorn
  2. Setting up your IDE (VS Code or PyCharm)
  3. Setting up Git and GitHub to track your project

Installing FastAPI and Uvicorn

With Python set up, the next step is installing FastAPI and Uvicorn. FastAPI is the framework we’ll use to build our applications, and Uvicorn is an ASGI server that runs and serves our FastAPI applications.

Open your command-line interface and install FastAPI and Uvicorn together by running the following command:

$ pip install fastapi[all]

This command installs FastAPI along with its recommended dependencies, including Uvicorn.

To verify the installation, you can simply run uvicorn --version from the terminal.

Setting up your IDE

Choosing the right IDE is a crucial step in your FastAPI journey. An IDE is more than just a text editor; it’s a space where you write, debug, and test your code.

A good IDE can significantly enhance your coding experience and productivity. For FastAPI development and Python in general, two popular choices are VS Code and PyCharm.

VS Code

VS Code is a free, open source, lightweight IDE with powerful features. It offers excellent Python support and is highly customizable.

You can download and install VS Code from the official website (code.visualstudio.com). The installation is quite straightforward. Once installed, open VS Code, go to Extensions (a square icon on the left bar), and search for python. Install the Microsoft version, and that is it.

PyCharm

PyCharm, created by JetBrains, is specifically tailored for Python development. It offers a broad range of tools for professional developers, including excellent support for web development frameworks such as FastAPI.

You can choose between a Community free edition and a Professional paid version. For the scope of the book, the Community Edition is largely sufficient, and it can be downloaded on the JetBrains website: https://www.jetbrains.com/pycharm/download/.

For PyCharm as well, the installation is straightforward.

Enhancing your development experience

For both IDEs – and if you use another of your choice – make sure to leverage basic perks to improve your experience as a developer and be more efficient. Here is a short checklist that I use when I approach a new IDE environment:

  • Code completion and analysis: Good IDEs provide intelligent code completion, error highlighting, and fixes, which are invaluable for efficient development
  • Debugging tools: Utilize debugging features provided by the IDE to diagnose and resolve issues in your code
  • Version control integration: A good IDE offers support for Git, simplifying code change tracking and repository management
  • Customization: Customize your IDE by adjusting themes, key binding, and settings to match your workflow, making your development experience as comfortable and productive as possible

Setting up Git and GitHub

Version control is an essential aspect of software development. Git, coupled with GitHub, forms a powerful toolset for tracking changes, collaborating, and maintaining the history of your projects. You can download the Git installer from the official website git-scm.com and install it.

After installation, configure Git with your username and email using the following commands in the command line:

$ git config --global user.name "Your Name"
$ git config --global user.email "your.email@example.com"

GitHub is the platform chosen to store code examples used in the book. Sign up for a GitHub account at github.com if you don’t already have one.

Creating a new FastAPI project

Setting up a well-organized project structure is crucial for maintaining a clean code base, especially as your application grows and evolves. This recipe will guide you on how to create your first basic FastAPI project. A structured project simplifies navigation, debugging, and collaboration. For FastAPI, following best practices in structuring can significantly enhance scalability and maintainability.

Getting ready

All you need to do to follow the recipe is make sure that you have your development environment set up.

How to do it...

We begin by making a project folder named fastapi_start that we’ll use as the root project folder.

  1. From the terminal at the root project folder level, we’ll set up our virtual environment by running the following command:
    $ python -m venv .venv

    This will create a .venv folder that will contain all packages required for the project within our project's root folder.

  2. Now, you need to activate the environment. If you are on Mac or Linux, run the following command:
    $ source .venv/bin/activate

    From Windows, run the following command:

    $ .venv\Scripts\activate

    When the environment is active, you should see in your terminal a prefix string such as (.venv) $. Alternatively, if you check the location of the python binary command, it should be located within the .venv folder. From now on, each time you install a module with pip, it will be installed in the .venv folder, and it will be activated only if the environment is active.

  3. Now, you can install the fastapi package with uvicorn in your environment by running the following command:
    $ pip install fastapi uvicorn

    Once FastAPI is installed in your environment, open your project folder with your favorite IDE and create a file called main.py.

  4. This file is where your FastAPI application begins. Start by writing the import of the FastAPI module. Then, create an instance of the FastAPI class:
    from fastapi import FastAPI
    app = FastAPI()

    This instance houses the code of your application.

  5. Next, define your first route. Routes in FastAPI are like signposts that direct requests to the appropriate function. Start with a simple route that returns a greeting to the world:
    @app.get("/")
    def read_root():
        return {"Hello": "World"}

    You’ve just created the code for your first FastAPI application.

If you want to track the project, you can set up Git as follows:

  1. In your project’s root directory, open a terminal or Command Prompt and run the following command:
    $ git init

    This simple command prepares your project for version control under Git.

    Before committing, create a .gitignore file to specify untracked files to ignore (such as __pychache__, .venv, or IDE-specific folders). You can also have a look at the one on the GitHub repository of the project at the link: https://github.com/PacktPublishing/FastAPI-Cookbook/blob/main/.gitignore.

  2. Then, add your files with the following command:
    $ git add .
  3. Then, commit them using the following command:
    $ git commit -m "Initial commit"

And that's it. You are now tracking your project with Git.

There’s more...

A well-structured project is not just about neatness; it’s about creating a sustainable and scalable environment where your application can grow and evolve. In FastAPI, this means organizing your project in a way that separates different aspects of your application logically and efficiently.

There is no unique and perfect structure for a FastAPI project; however, a common approach is to divide your project into several key directories:

  • /src: This is where your primary application code lives. Inside /src, you might have subdirectories for different modules of your application. For instance, you could have a models directory for your database models, a routes directory for your FastAPI routes, and a services directory for business logic.
  • /tests: Keeping your tests separate from your application code is a good practice. It makes it easier to manage them and ensures that your production builds don’t include test code.
  • /docs: Documentation is crucial for any project. Whether it’s API documentation, installation guides, or usage instructions, having a dedicated directory for documentation helps maintain clarity.

See also

You can find detailed information on how to manage virtual environments with venv at the following link:

To brush up your knowledge with Git and get familiar with adding, staging and commiting operations, have a look at this guide:

Understanding FastAPI basics

As we embark on our journey with FastAPI, it’s essential to build a solid foundation. FastAPI isn’t just another web framework; it’s a powerful tool designed to make your life as a developer easier, your applications faster, and your code more robust and maintainable.

In this recipe, we’ll demystify the core concepts of FastAPI, delve into its unique features such as asynchronous programming, and guide you through creating and organizing your first endpoints. By the end of the recipe, you’ll have your first FastAPI server up and running – a milestone that marks the beginning of an exciting journey in modern web development.

FastAPI is a modern, fast web framework for building APIs with Python based on standard Python type hints.

Key features that define FastAPI are the following:

  • Speed: It’s one of the fastest frameworks for building APIs in Python, thanks to its underlying Starlette framework for web parts and Pydantic for data handling
  • Ease of use: FastAPI is designed to be easy to use, with intuitive coding that accelerates your development time
  • Automatic documentation: With FastAPI, the API documentation is generated automatically, a feature that is both a time-saver and a boon for developers

How to do it…

We will now explore how to use those features effectively with some general guidance.

We will go through the following steps:

  • Applying asynchronous programming to our existing endpoints to improve time efficiency
  • Exploring routers and endpoints to better organize large code bases
  • Running your first FastAPI server with a basic configuration
  • Exploring the automatic documentation

Applying asynchronous programming

One of the most powerful features of FastAPI is its support for asynchronous programming. This allows your applications to handle more requests simultaneously, making them more efficient. Asynchronous programming is a style of concurrent programming in which tasks are executed without blocking the execution of other tasks, improving the overall performance of your application. To integrate asynchronous programming smoothly, FastAPI leverages the async/await syntax (https://fastapi.tiangolo.com/async/) and automatically integrates asynchronous functions.

So, the read_root() function in main.py from the previous code snippet in the Creating a new FastAPI project recipe can be written as follows:

@app.get("/")
async def read_root():
    return {"Hello": "World"}

In this case, the behavior of the code will be exactly the same as before.

Exploring routers and endpoints

In FastAPI, organizing your code into routers and endpoints is a fundamental practice. This organization helps in making your code cleaner and more modular.

Endpoints

Endpoints are the points at which API interactions happen. In FastAPI, an endpoint is created by decorating a function with an HTTP method, such as @app.get("/").

This signifies a GET request to the root of your application.

Consider the following code snippet:

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
    return {"Hello": "World"}

In this snippet, we define an endpoint for the root URL ("/"). When a GET request is made to this URL, the read_root function is invoked, returning a JSON response.

Routers

When we need to handle multiple endpoints that are in different files, we can benefit from using routers. Routers assist us in grouping our endpoints into different modules, which makes our code base easier to maintain and understand. For example, we could use one router for operations related to users and another for operations related to products.

To define a router, first create a new file in the fastapi_start folder called router_example.py. Then, create the router as follows:

from fastapi import APIRouter
router = APIRouter()
@router.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

You can now reuse it and attach the router to the FastAPI server instance in main.py:

import router_example
from fastapi import FastAPI
app = FastAPI()
app.include_router(router_example.router)
@app.get("/")
async def read_root():
    return {"Hello": "World"}

You now have the code to run the server that includes the router for the GET /items endpoint importer from another module.

Running your first FastAPI server

To run your FastAPI application, you need to point Uvicorn to your app instance. If your file is named main.py and your FastAPI instance is called app, you can start your server like this at the fastapi_start folder level:

$ uvicorn main:app --reload

The --reload flag makes the server restart after code changes, making it ideal for development.

Once the server is running, you can access your API at http://127.0.0.1:8000. If you visit this URL in your browser, you’ll see the JSON response from the "/" endpoint we have just created.

Exploring the automatic documentation

One of the most exciting features of FastAPI is its automatic documentation. When you run your FastAPI application, two documentation interfaces are automatically generated: Swagger UI and Redoc.

You can access these at http://127.0.0.1:8000/docs for Swagger UI and http://127.0.0.1:8000/redoc for Redoc.

These interfaces provide an interactive way to explore your API and test its functionality.

See also

You can discover more about what we covered in the recipe at the following links:

Defining your first API endpoint

Now that you have a fundamental grasp of FastAPI and your development environment is all set up, it’s time to take the next thrilling step: creating your first API endpoint.

This is where the real magic of FastAPI begins to shine. You’ll see how effortlessly you can build a functional API endpoint, ready to respond to HTTP requests.

In this recipe, you will create a basic draft of a backend service for a bookstore.

Getting ready

Make sure you know how to start a basic FastAPI project from the Creating a new FastAPI project recipe.

How to do it...

In the realm of web APIs, the GET request is perhaps the most common. It’s used to retrieve data from the server. In FastAPI, handling a GET request is simple and intuitive. Let’s create a basic GET endpoint.

Imagine you’re building an API for a bookstore. Your first endpoint will provide information about a book when given its ID. Here’s how you do it:

  1. Create a new bookstore folder that will contain the code you are going to write.
  2. Create in it a main.py file containing the server instance:
    from fastapi import FastAPI
    app = FastAPI()
    @app.get("/books/{book_id}")
    async def read_book(book_id: int):
        return {
            "book_id": book_id,
            "title": "The Great Gatsby",
            "author": "F. Scott Fitzgerald"
        }

In the preceding code snippet, the @app.get("/books/{book_id}") decorator tells FastAPI that this function will respond to GET requests at the /books/{book_id} path. {book_id} in the path is a path parameter, which you can use to pass values dynamically. FastAPI automatically extracts the book_id parameter and passes it to your function.

Type hints and automatic data validation

Notice the use of type hints (book_id: int). FastAPI uses these hints to perform data validation. If a request is made with a non-integer book_id parameter, FastAPI automatically sends a helpful error response.

How it works…

With your GET endpoint defined, run your FastAPI application using Uvicorn, just as you did previously:

$ uvicorn main:app --reload

On the terminal, you can read the message logs describing that the server is running on port 8000.

One of FastAPI’s most beloved features is its automatic generation of interactive API documentation using Swagger UI. This tool allows you to test your API endpoints directly from your browser without writing any additional code, and you can directly check the presence of the newly created endpoint in it.

Using Swagger UI

To test your new GET endpoint, navigate to http://127.0.0.1:8000/docs in your browser. This URL brings up the Swagger UI documentation for your FastAPI application. Here, you’ll see your /books/{book_id} endpoint listed. Click on it, and you’ll be able to execute a test request right from the interface. Try inputting a book ID and see the response your API generates.

Postman – a versatile alternative

While Swagger UI is convenient for quick tests, you might want to use a more robust tool such as Postman for more complex scenarios. Postman is an API client that lets you build, test, and document your APIs more extensively.

To use Postman, download and install it from Postman’s website (https://www.postman.com/downloads/).

Once installed, create a new request. Set the method to GET and the request URL to your FastAPI endpoint, http://127.0.0.1:8000/books/1. Hit Send, and Postman will display the response from your FastAPI server.

Working with path and query parameters

One of the most crucial aspects of API development is handling parameters. Parameters allow your API to accept input from users, making your endpoints dynamic and responsive.

In this recipe, we will explore how to capture and handle path, query parameters, and test them efficiently, enhancing the flexibility and functionality of your FastAPI applications.

Getting ready

To follow the recipe, make sure you know how to create a basic endpoint from the previous recipe.

How to do it…

Path parameters are parts of the URL that are expected to change. For instance, in an endpoint such as /books/{book_id}, book_id is a path parameter. FastAPI allows you to capture these parameters effortlessly and use them in your function.

  1. Let’s expand our bookstore API with a new endpoint that uses path parameters. This time, we’ll create a route to get information about a specific author:
    @app.get("/authors/{author_id}")
    async def read_author(author_id: int):
        return {
            "author_id": author_id,
            "name": "Ernest Hemingway"
        }

    The name will not change; however, the author_id value will be the one provided by the query request.

    Query parameters are used to refine or customize the response of an API endpoint. They can be included in the URL after a question mark (?). For instance, /books?genre=fiction&year=2010 might return only books that fall under the fiction genre released in 2010.

  2. Let’s add query parameters to our existing endpoint. Suppose we want to allow users to filter books by their publication year:
    @app.get("/books")
    async def read_books(year: int = None):
        if year:
            return {
                "year": year,
                "books": ["Book 1", "Book 2"]
            }
        return {"books": ["All Books"]}

Here, year is an optional query parameter. By assigning None as a default value, we make it optional. If a year is specified, the endpoint returns books from that year; otherwise, it returns all books.

Exercise

Using the APIRouter class, refactor each endpoint in a separate file and add the route to the FastAPI server.

How it works…

Now, from the command terminal, spin up the server with Uvicorn by running the following command:

$ uvicorn main:app

Testing endpoints with path parameters can be done using Swagger UI or Postman, similar to how we tested our basic GET endpoint.

In Swagger UI, at http://localhost:8000/docs, navigate to your /authors/{author_id} endpoint. You’ll notice that it prompts you to enter an author_id value before you can try it out. Enter a valid integer and execute the request. You should see a response with the author’s information.

The GET /books endpoint will now show an optional field for the year query parameter. You can test it by entering different years and observing the varying responses.

If you use Postman instead, create a new GET request with the http://127.0.0.1:8000/authors/1 URL. Sending this request should yield a similar response.

In Postman, append the query parameter to the URL like so: http://127.0.0.1:8000/books?year=2021. Sending this request should return books published in the year 2021.

See also

You can find more about path and query parameters in the FastAPI official documentation at the following links:

Defining and using request and response models

In the world of API development, data handling is a critical aspect that determines the robustness and reliability of your application. FastAPI simplifies this process through its seamless integration with Pydantic, a data validation and settings management library using Python type annotations. The recipe will show you how to define and use request and response models in FastAPI, ensuring your data is well structured, validated, and clearly defined.

Pydantic models are a powerful feature for data validation and conversion. They allow you to define the structure, type, and constraints of the data your application handles, both for incoming requests and outgoing responses.

In this recipe, we will see how to use Pydantic to ensure that your data conforms to the specified schema, providing an automatic layer of safety and clarity.

Getting ready

This recipe requires you to know how to set up a basic endpoint in FastAPI.

How to do it...

We will break the process into the following steps:

  1. Creating the model
  2. Defining the request body
  3. Validating request data
  4. Managing response formats

Creating the model

Let’s create a Pydantic BaseModel class for our bookstore application in a new file called models.py.

Suppose we want to have a model for a book that includes the title, author, and publication year:

from pydantic import BaseModel
class Book(BaseModel):
    title: str
    author: str
    year: int

Here, Book is a Pydantic BaseModel class with three fields: title, author, and year. Each field is typed, ensuring that any data conforming to this model will have these attributes with the specified data types.

Defining the request body

In FastAPI, Pydantic models are not just for validation. They also serve as the request body. Let’s add an endpoint to our application where users can add new books:

from models import Book
@app.post("/book")
async def create_book(book: Book):
    return book

In this endpoint, when a user sends a POST request to the /book endpoint with JSON data, FastAPI automatically parses and validates it against the Book model. If the data is invalid, the user gets an automatic error response.

Validating request data

Pydantic offers advanced validation features. For instance, you can add regex validations, default values, and more:

from pydantic import BaseModel, Field
class Book(BaseModel):
    title: str = Field(..., min_length=1, max_length=100)
    author: str = Field(..., min_length=1, max_length=50)
    year: int = Field(..., gt=1900, lt=2100)

For an exhaustive list of validation features, have a look at Pydantic’s official documentation: https://docs.pydantic.dev/latest/concepts/fields/.

Next, you can proceed to manage the response format.

Managing response formats

FastAPI allows you to define response models explicitly, ensuring that the data returned by your API matches a specific schema. This can be particularly useful for filtering out sensitive data or restructuring the response.

For example, let’s say you want the /allbooks GET endpoint to return a list of books, but only with their titles and authors, omitting the publication year. In main.py, add the following accordingly:

from pydantic import BaseModel
class BookResponse(BaseModel):
    title: str
    author: str
@app.get("/allbooks")
async def read_all_books() -> list[BookResponse]:
    return [
        {
            "id": 1,
            "title": "1984",
            "author": "George Orwell"},
        {
            "id": 1,
            "title": "The Great Gatsby",
            "author": "F. Scott Fitzgerald",
        },
    ]

Here, the -> list[BookResponse] function type hint tells FastAPI to use the BookResponse model for responses, ensuring that only the title and author fields are included in the response JSON. Alternatively, you can specify the response type in the endpoint decorator’s arguments as follows:

@app.get("/allbooks", response_model= list[BookResponse])
async def read_all_books() -> Any:
# rest of the endpoint content

The response_model argument takes priority and can be used instead of the type hint to resolve type checker issues that may occur.

Check the documentation at http://127.0.0.1:8000/docs. Unroll the /allbooks endpoint details, and you will notice the example value response based on the schema as follows:

[
  {
    "title": "string",
    "author": "string"
  }
]

By mastering Pydantic models in FastAPI, you are now capable of handling complex data structures with ease and precision. You’ve learned to define request bodies and manage response formats, ensuring data consistency and integrity throughout your application.

See also

Pydantic is a standalone project largely used for data validation in Python with many more features than what the recipe has shown. Feel free to have a look at the official documentation at the following link:

You can see more on response model usage at the FastAPI official documentation link:

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:

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore FastAPI in depth, from basic setup to advanced features such as custom middleware and WebSockets
  • Discover practical strategies to optimize app performance and handle high traffic
  • Implement SQL and NoSQL integration techniques for versatile data management in FastAPI applications
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

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.

What you will learn

  • Explore advanced FastAPI functionalities such as dependency injection, custom middleware, and WebSockets
  • Discover various types of data storage for powerful app functionality with SQL and NoSQL
  • Implement testing and debugging practices for clean, robust code
  • Integrate authentication and authorization mechanisms to secure web apps
  • Acquire skills to seamlessly migrate existing applications to FastAPI
  • Write unit and integration tests, ensuring reliability and security for your apps
  • Deploy your FastAPI apps to production environments for real-world use

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 2, 2024
Length 358 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781805127857
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon AI Assistant (beta) to help accelerate your learning
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Aug 2, 2024
Length 358 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781805127857
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Table of Contents

15 Chapters
Preface Chevron down icon Chevron up icon
1. Chapter 1: First Steps with FastAPI Chevron down icon Chevron up icon
2. Chapter 2: Working with Data Chevron down icon Chevron up icon
3. Chapter 3: Building RESTful APIs with FastAPI Chevron down icon Chevron up icon
4. Chapter 4: Authentication and Authorization Chevron down icon Chevron up icon
5. Chapter 5: Testing and Debugging FastAPI Applications Chevron down icon Chevron up icon
6. Chapter 6: Integrating FastAPI with SQL Databases Chevron down icon Chevron up icon
7. Chapter 7: Integrating FastAPI with NoSQL Databases Chevron down icon Chevron up icon
8. Chapter 8: Advanced Features and Best Practices Chevron down icon Chevron up icon
9. Chapter 9: Working with WebSocket Chevron down icon Chevron up icon
10. Chapter 10: Integrating FastAPI with other Python Libraries Chevron down icon Chevron up icon
11. Chapter 11: Middleware and Webhooks Chevron down icon Chevron up icon
12. Chapter 12: Deploying and Managing FastAPI Applications Chevron down icon Chevron up icon
13. Index Chevron down icon Chevron up icon
14. Other Books You May Enjoy Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.