You can provide default values to the query parameters.
Example
@app.get("/emps")
def emps(pageNum : int = 1, pageSize : int = 10):
return {'received' : {'pageNum' : pageNum, 'pageSize': pageSize}}
In the example above, api is defined with default values of pageNum=1 and pageSize=10. When FastAPI do not receive any query parameter, it will considers default value, below table summarizes the same.
URL |
pageNum and pageSize |
http://127.0.0.1:8000/emps |
{"pageNum":1,"pageSize":10} |
http://127.0.0.1:8000/emps?pageNum=8 |
{"pageNum":8,"pageSize":10} |
http://127.0.0.1:8000/emps?pageSize=8 |
{"pageNum":1,"pageSize":8} |
http://127.0.0.1:8000/emps?pageSize=8&pageNum=7 |
{"pageNum":7,"pageSize":8} |
defaultValuesToQueryParam.py
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/")
def home():
return {'name' : 'Hello World app', 'version': '2.0.0'}
@app.get("/emps")
def emps(pageNum : int = 1, pageSize : int = 10):
return {'received' : {'pageNum' : pageNum, 'pageSize': pageSize}}
Open terminal and execute the command ‘uvicorn defaultValuesToQueryParam:app --reload'
from fastapi import FastAPI, Path app = FastAPI() @app.get("/") def home(): return {'name' : 'Hello World app', 'version': '2.0.0'} @app.get("/emps") def emps(pageNum : int = 1, pageSize : int = 10): return {'received' : {'pageNum' : pageNum, 'pageSize': pageSize}}
Open the url ‘http://127.0.0.1:8000/docs’ and experiment with the api.
Previous Next Home
No comments:
Post a Comment