2

I am trying to make two services communicate. The first API is exposed to the user. The second is hidden and can process files. So the first can redirect requests. I want to make of the post request asynchronus using aiohttp but i am facing this error : "There was an error parsing the body"

To recreate the error : Lets say this is the server code

from fastapi import FastAPI
from fastapi import UploadFile, File

app = FastAPI()

@app.post("/upload")
async def transcript_file(file: UploadFile = File(...)):
    pass

And this is the client code :

from fastapi import FastAPI
import aiohttp
app = FastAPI()

@app.post("/upload_client")
async def async_call():
    async with aiohttp.ClientSession() as session:
        headers = {'accept': '*/*',
                   'Content-Type': 'multipart/form-data'}
        file_dict = {"file": open("any_file","rb")}
        async with session.post("http://localhost:8000/upload", headers=headers, data=file_dict) as response:
            return await response.json()

Description :

  • Run the server on port 8000 and the client on any port you like
  • Open the browser and open docs on the client.
  • Execute the post request and see the error

Environment :

  • aiohttp = 3.7.4
  • fastapi = 0.63.0
  • uvicorn = 0.13.4
  • python-multipart = 0.0.2

Python version: 3.8.8

Hosten
  • 138
  • 1
  • 11

1 Answers1

3

From this answer:

If you are using one of multipart/* content types, you are actually required to specify the boundary parameter in the Content-Type header, otherwise the server (in the case of an HTTP request) will not be able to parse the payload.

You need to remove the explicit setting of the Content-Type header, the client aiohttp will add it implicitly for you, including the boundary parameter.

alex_noname
  • 26,459
  • 5
  • 69
  • 86