Query parameters and optional parameters
FastAPI is a cutting-edge Python framework that uses Python 3.6+ type declarations to produce robust, efficient, and easy-to-read code. In this article, we will discuss how to use query parameters and optional parameters in FastAPI.
Query Parameters
Query parameters are the key-value pairs that you see in the URL after the ?
. They are part of the URL but are not part of the path. Let's see how to define them in FastAPI.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = None):
return {"q": q}
In the above code, q
is a query parameter of string type. If you run this application and hit the URL http://localhost:8000/items/?q=somequery
, you will get the response {"q": "somequery"}
.
Optional Parameters
In FastAPI, you can make any parameter optional by using Optional
from the typing
module. An optional parameter is a query parameter that the client can choose to include or not.
Let's modify the previous example to make the query parameter optional.
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(q: Optional[str] = None):
return {"q": q}
In this code, q
is an optional query parameter. If you call the URL http://localhost:8000/items/
, you will get the response {"q": null}
.
Multiple Query Parameters
FastAPI also supports multiple query parameters. You can add as many as you want. Here is an example:
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(q: Optional[str] = None, page: int = 1, size: int = 10):
return {"q": q, "page": page, "size": size}
In this code, we have three query parameters: q
, page
, and size
. If you hit the URL http://localhost:8000/items/?q=somequery&page=2&size=5
, you will get the response {"q": "somequery", "page": 2, "size": 5}
.
Default Values
You can also provide default values to the query parameters that will be used when the client does not provide them.
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(q: Optional[str] = None, page: int = 1, size: int = 10):
return {"q": q, "page": page, "size": size}
In this code, page
and size
have default values. So, if you hit the URL http://localhost:8000/items/?q=somequery
, you will get the response {"q": "somequery", "page": 1, "size": 10}
.
That wraps up our discussion on query parameters and optional parameters in FastAPI. These features allow you to create flexible APIs that can handle a variety of client requests. As you progress with FastAPI, you'll find these tools extremely useful in creating robust, efficient, and readable APIs.