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.
- 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. - 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:
- Path Parameters: https://fastapi.tiangolo.com/tutorial/path-params/
- Query Parameters: https://fastapi.tiangolo.com/tutorial/query-params/