python-requestsfastapiuvicornhttp-status-code-422

FastAPI file upload


I am trying to upload JSON data + file (binary) to FastAPI 'POST' endpoint using requests.

This is the server code:

@app.post("/files/")
async def create_file(
    file: bytes = File(...), fileb: UploadFile = File(...), timestamp: str = Form(...)
):
    return {
        "file_size": len(file),
        "timestamp": timestamp,
        "fileb_content_type": fileb.content_type,
    }

This is the client code:

session = requests.Session()
adapter = requests.adapters.HTTPAdapter(max_retries=0)
session.mount('http://', adapter)

jpg_image = open(IMG_PATH, 'rb').read()

timestamp_str = datetime.datetime.now().isoformat()
files = {
    'timestamp': (None, timestamp_str),
    'file': ('image.jpg', jpg_image),
}
request = requests.Request('POST',
                           FILE_UPLOAD_ENDPOINT,
                           files=files)
prepared_request = request.prepare()
response = session.send(prepared_request)

The server fails with

"POST /files/ HTTP/1.1" 422 Unprocessable Entity


Solution

  • FastAPI endpoints usually respond 422 when the request body is missing a required field, or there are non-expected fields, etc.

    It seems that you are missing the fileb from your request body.