Is there a way that I can extract the key-value pair of the optional path parameter?
lets say that I have the following code:
@app.get("/users")
async def request(userEmail = None, organization = None):
and I send the get request to the following url: http://127.0.0.1:8000/users?userEmail=test@test.com&organization=testOrg
Is there a way that I can extract the key-value pair of the optional path parameter so that I can get
{"userEmail" : "test@test.com", "organization" : "testOrg"}
Or if http://127.0.0.1:8000/users?userEmail=test@test.com , then
{"userEmail" : "test@test.com"}
You can use the Request object, from starlette library
from fastapi import Request
@app.get("/users")
async def users(request: Request,
userEmail = None, organization = None):
print(request.query_params)
Query parameters are exposed as an immutable multi-dict.
reference https://www.starlette.io/requests/#query-parameters
You can use request.query_params._dict it will extract in key-value pairs.
from fastapi import Request
@app.get("/users")
async def users(request: Request,
userEmail = None, organization = None):
print(request.query_params._dict)
if you hit request: http://127.0.0.1:8000/users?userEmail=test@test.com&organization=testOrg
it will give you {"userEmail":"test@test.com","organization":"testOrg"}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.