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

Question:

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)
Asked By: MGLondon

||

Answers:

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.

Answered By: Chris
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.