Hello
I am a data scientist new in building API's. I developed a REST API using Fast API and I use python's library requests to call the API.
However, I don't know how to pass a list parameter (e;g. : ['a', 'b', ...])
I have declared the parameter in FastAPI as List[str], I also tried is declare it inside a BaseModel class as a list but this didn't work for me.
I couldn't figure out the problem. Anyone can help with an example, please?
in addition, I would like to know how do send the list in the requests library? I already use params and files but I don't know where a list can be sent.
Thank you in advance.
Can you share your code?
You are taking into account that lists or python objects in general have to be sent and received as JSON, right?
@amineHY here are a couple examples to get you pointed in the right direction. First endpoint shows a list as a query param for a GET request. The second shows the list in a JSON body for a POST request. You could also do the same for a Form I believe.
Note that here calls to client.post and client.get use the same syntax as requests.post and requests.get:
from typing import List
import fastapi
from fastapi.params import Query
from starlette.testclient import TestClient
app = fastapi.FastAPI()
@app.get("/")
def get(data: List[str] = Query(...)):
print(data)
@app.post("/")
def post(data: List[str]):
print(data)
if __name__ == '__main__':
client = TestClient(app)
print(client.post("/", json=["1", "2"]))
print(client.get("/", params={"data": ["3", "4"]}))
I found one mention of this in the docs here though for some reason it's in a section about str validation, so maybe that should be moved elsewhere.
Hi @dbanty,
Thank you for your help, your example works very well. The problem for me seems to be from the way I send a request from the client:
requests.get("http://127.0.0.1:8000", params={"data": ["3", "4"]})
TestClient allows me to overcome this limitation, I will switch from requests library to TestClient since it is built on top of it
Thanks for the help here everyone! :clap: :bow:
Thanks for reporting back and closing the issue :+1:
Most helpful comment
@amineHY here are a couple examples to get you pointed in the right direction. First endpoint shows a list as a query param for a GET request. The second shows the list in a JSON body for a POST request. You could also do the same for a Form I believe.
Note that here calls to
client.postandclient.getuse the same syntax asrequests.postandrequests.get:I found one mention of this in the docs here though for some reason it's in a section about str validation, so maybe that should be moved elsewhere.