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

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.

Leave a Comment