Query parameter
- Python course
- Advanced
- Lesson 53/83
- 5 min
Learn query parameters with ?q=value.
Query parameter
If a function parameter is not in the path, FastAPI treats it as a query parameter. It is taken from the ?key=value part of the URL.
@app.get("/ara")
def ara(q: str = None):
return {"q": q}
# /ara?q=kalem -> {"q": "kalem"}If you give a default value, the parameter becomes optional; otherwise it is required. You can also give a type (int, str).
Required and optional
If you give a query parameter a default value (q: str = None) it becomes optional. Without one (q: str) it is required; if missing from the URL, 422 is returned.
# optional
@app.get("/ara")
def ara(q: str = None): ...
# required
@app.get("/ara")
def ara(q: str): ...The default can be an empty string ("") or any other constant. This is useful for fields like search that can be left blank.
Practice GET route with a query parameter
Start with from fastapi import FastAPI and from fastapi.testclient import TestClient. Define app = FastAPI(). With @app.get("/ara") define def ara(q: str = None): returning {"q": q}. Create a client with client = TestClient(app). Print the response body with print(client.get("/ara?q=kalem").text).
Starter code
# bring in FastAPI from fastapi
# bring in TestClient
# define app
# add a get function at '/ara' (with q: str = None parameter)
# create a client with TestClient, query '/ara?q=kalem' and print the bodySample solution
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/ara")
def ara(q: str = None):
return {"q": q}
client = TestClient(app)
print(client.get("/ara?q=kalem").text)Expected output
{"q":"kalem"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the function with a query parameter
@app.get("/ara")
def ara(____: str = None):
return {"q": q}
@app.get("/ara")
def ara(q: str = None):
return {"q": q}
Explanation: str = None becomes a query parameter.
2 Which URL sends the query parameter q=kalem to /ara?
- /ara&q=kalem
- /ara/q/kalem
- /ara#q=kalem
- /ara?q=kalem Correct answer
Explanation: The part starting with ? carries the query parameters.
3 Match the query parameter concepts
| Term | Meaning |
|---|---|
q: str = None |
Is optional |
q: str |
Is required |
?q=kalem |
Is a URL query |
def ara(q) |
Is the function definition |