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

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:

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 $19.99/month. Cancel anytime