How to post request JSON to fastapi, and retrieve whole JSON in the post function

Viewed 2277

I want 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 seeing an error:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
1 Answers

You should use json parameter instead (which will change the Content-Type in the header to application/json), not data which is used for sending form data. Also, please have a look at the documentation on how to benefit from using Pydantic models for request bodies.

response = requests.post(api_url, json=data)
Related