In this post, we will learn how to use FastAPI query parameters while creating API endpoints. Query parameters are absolutely vital to build flexible APIs. As the name suggests, endpoints with query parameters can often help clients to query for specific data based on dynamic parameters.

In the last post, we learnt how to use FastAPI path parameters. We will be building upon the same foundation in this post with examples.

1 – Query Parameters

In FastAPI, when we declare a function with parameters that are not present as path parameters, they are interpreted as query parameters.

See below example:

from fastapi import FastAPI

app = FastAPI()

movies_db = [{"movie_name": "The Fellowship of the Ring"}, {"movie_name": "The Two Towers"}, {"movie_name": "The Return of the King"}]

@app.get("/movies/" )
def get_movie(skip: int = 0, limit: int = 10):
    return movies_db[skip: skip + limit]

As you can see, we have two parameters skip and limit. These parameters are not part of the path parameters. Instead, they are provided in the form of query parameters while invoking the API endpoint as http://localhost:8000/movies?skip=0&limit=10.

Here, skip has a value of 0 and limit has a value of 10. Since they are part of the URL, they are treated as strings. However, we declare them with Python types. Due to this, they are automatically converted and validated against it.

2 – Query Parameter Default Value

As we can see, query parameters are not part of the fixed path. Hence, they are optional. Also, they can have default values in case we don’t pass any value as input.

In other words, if we simply call http://localhost:8000/movies, this would mean that skip will take the default value of 0 and limit will take default value of 10. This is as per the function definition.

@app.get("/movies/" )
def get_movie(skip: int = 0, limit: int = 10):
    return movies_db[skip: skip + limit]

In case we call http://localhost:8000/movies?skip=1, default value will be applicable only for limit. The value of skip will be 1. Output will be as follows:

[{
	"movie_name": "The Two Towers"
}, {
	"movie_name": "The Return of the King"
}]

3 – Declaring a Parameter Optional

We can also specify a parameter as optional by setting the default value to None.

See below example:

from typing import Optional

from fastapi import FastAPI

app = FastAPI()

@app.get("/movies/{movie_id}")
def get_movie(movie_id: str, optional: Optional[str] = None):
    if optional:
        return {"movie_id": movie_id, "optional": optional}
    return {"movie_id": movie_id}

Here, movie_id is a path parameter. The parameter optional is optional. Its value is None by default.

beenhere

Info

Note here that the Optional in Optional[str] is not used by FastAPI. The framework only uses the str part to provide editor support for the parameter data type.

4 – Query Parameter Type Conversion

FastAPI also supports automatic type conversion for query parameters.

Consider the below example:

@app.get("/movie-description/{book_name}")
def get_movie_description(book_name: str, description: bool = True):
    book = {"book_name": book_name}

    if description:
        book.update({"book_description": "This is a fantastic book"})

    return book

In the above snippet, the parameter description is a bool. When we call the endpoint http://localhost:8000/movie-description/eotw?description=0, the value 0 for the description is converted to boolean False.

FastAPI also converts other combinations such as below to boolean False:

http://localhost:8000/movie-description/eotw?description=off

http://localhost:8000/movie-description/eotw?description=false

http://localhost:8000/movie-description/eotw?description=no

5 – Multiple Path and Query Parameters

We can also declare multiple path and query parameters together. Also, the order of declaring them in the function definition is not important. FastAPI detects them by name.

See below example:

@app.get("/books/{book_id}/authors/{author_id}")
def get_book_details(book_id: int, author_id: int, description: bool = True):
    book_detail = {"book_id": book_id, "author_id": author_id}

    if description:
        book_detail.update({"book_description": "This is the description"})

    return book_detail

Here, book_id and author_id are path parameters. Description is a query parameter.

6 – Mandatory Query Parameters

When we declare a query parameter with default value, we make it optional. Also, when we keep the default value None, FastAPI treats it as optional.

However, we can also make certain query parameters mandatory. Basically, we don’t have to supply a default value. In such a case, FastAPI treats the query parameter as mandatory.

See below example.

@app.get("/books/{book_id}/authors/{author_id}")
def get_book_details_with_description(book_id: int, author_id: int, description: bool):
    book_detail = {"book_id": book_id, "author_id": author_id, "description" : "This is mandatory description"}

    return book_detail

Here, description does not have a default value. In other words, it is mandatory.

If we don’t supply an input value, we get the below error response.

{
	"detail": [{
		"loc": ["query", "description"],
		"msg": "field required",
		"type": "value_error.missing"
	}]
}

Conclusion

With this, we have successfully learnt how to use FastAPI Query Parameters in our API endpoints. We looked at default values, making parameters optional and also mandatory.

If you have any comments or queries, please feel free to write in the comments section below.

Categories: BlogFastAPI

Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *