How to post JSON data to FastAPI and retrieve the JSON data inside the endpoint?
Asked Answered
Q

1

7

I would like to pass a JSON object to a FastAPI backend. Here is what I am doing in the frontend app:

data = {'labels': labels, 'sequences': sequences}
response = requests.post(api_url, data = data)

Here is how the backend API looks like in FastAPI:

@app.post("/api/zero-shot/")
async def Zero_Shot_Classification(request: Request):
    data = await request.json()

However, I am getting this error:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Quadrennium answered 3/2, 2022 at 17:0 Comment(0)
L
7

You should use the json parameter instead (which would change the Content-Type header to application/json):

payload = {'labels': labels, 'sequences': sequences}
r = requests.post(url, json=payload)

not data which is used for sending form data with the Content-Type being application/x-www-form-urlencoded by default, or multipart/form-data if files are also included in the request—unless you serialised your JSON first and manually set the Content-Type header to application/json, as described in this answer:

payload = {'labels': labels, 'sequences': sequences}
r = requests.post(url, data=json.dumps(payload), headers={'Content-Type': 'application/json'})

Also, please have a look at the documentation on how to benefit from using Pydantic models when sending JSON request bodies, as well as this answer and this answer for more options and examples on how to define an endpoint expecting JSON data.

Liesa answered 3/2, 2022 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.