so say if I had a dictionary {"userId":"bob","password":"12345"} how can I pass that as a query paramater in a get request in fastapi. I know I can use the Requests class but that returns it as a string not a dictionary.
so say if I had a dictionary {"userId":"bob","password":"12345"} how can I pass that as a query paramater in a get request in fastapi. I know I can use the Requests class but that returns it as a string not a dictionary.
If you define a parameter with type Request, you can use it's members as you like. The following would return your requirement. It will run as-is, you can run it immediately.
EDIT: The question was around passing a dict into an API. You can't do that with query parameters (which can only be simple types) but you can use a POST endpoint that accepts an arbitrary dictionary. See the below test.
from fastapi import FastAPI, Query, Request
app = FastAPI()
@app.get("/test_with_arbitrary_query_params")
async def root(request: Request):
return request.query_params._dict
@app.post("/test_with_dict")
async def root2(input: dict[str, str] = None):
return input
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Using curl:
curl -X GET localhost:8000/test_with_arbitrary_query_params -G -d 'userId=usr' -d 'password=pwd'
results in {"userId":"usr","password":"pwd"}.
The endpoint that accepts a dict, can be tried from either the automated docs, or also with curl:
curl -X POST localhost:8000/test_with_dict -H 'Content-Type: application/json' -d '{"userId":"usr","password":"pwd"}'
Response: {"userId":"usr","password":"pwd"}
Using multiple body parameters (in the dict form you're looking for) can be used like this from FastAPI docs.