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

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:

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