...

/

Default and Optional Query Parameters in FastAPI

Default and Optional Query Parameters in FastAPI

Learn and implement default and optional query parameters using FastAPI.

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:

Press + to interact
{{EDUCATIVE_LIVE_VM_URL}}/courses/

It would be the ...