Default and Optional Query Parameters in FastAPI
Explore how to set and use default and optional query parameters in FastAPI applications. Understand how these parameters improve API flexibility, enabling dynamic handling of user input and enhancing RESTful API functionality.
We'll cover the following...
We'll cover the following...
Default query parameters
As query parameters are not a fixed part of a path, they can be optional and can have default values. You can assign a default value to the query parameters as shown in the below code:
from fastapi import FastAPI
app = FastAPI()
course_items = [{"course_name": "Python"}, {"course_name": "NodeJS"}, {"course_name": "Machine Learning"}]
@app.get("/courses")
def read_courses(start: int = 0, end: int = 10):
return course_items[start : start + end]Default query parameters in FastAPI
In the example above, we have set the default values of start = 0 and end = 10. So, when we go to the URL:
It would be the same as going to:
But if we go to, for example:
The parameter values in our ...