How to pass query parameters in Python FastAPI ?
Once you have installed FastAPI, let’s see how to pass query parameters in FastAPI.
Here I have defined an endpoint in my FastAPI
app.
from fastapi import FastAPI
my_app = FastAPI()
@my_app.get("/getUserInfo")
def getUserInfo():
return [{
"id" : 100,
"firstName" : "roy"
}]
You can run the app using uvicorn app:my_app
. It will run an app on http://localhost:8000. You will be able to access the endpoint at http://localhost:8000/getUserInfo.
To pass query parameters to the above endpoint, the URL will look like, http://localhost:8000/getUserInfo?id=100&name=sam.
You can access the query parameters passed to the endpoint by defining the variable in the getUserInfo
method as parameters:
from fastapi import FastAPI
my_app = FastAPI()
@my_app.get("/getUserInfo")
def getUserInfo(id: int, name: str):
return [{
"id" : id,
"firstName" : name
}]
Save the changes and restart the server. Point your browser to http://localhost:8000/getUserInfo?id=100&name=tom and you will get passed id
and name
in the response JSON.
[{"id":100,"firstName":"tom"}]