Ali Gökkaya
Ali Gökkaya

Reputation: 488

I need to send files and data through FastAPI. I'm trying to send requests but couldn't get it to work

I need to send files and data through FastAPI. I'm trying to send requests but couldn't get it to work

for example :

server:

import uvicorn
from fastapi import FastAPI, File
from pydantic import BaseModel


app = FastAPI()


class Data(BaseModel):
    test1: str = None
    test2: str = None
    test3: str = None


@app.post("/uploadfile/")
async def create_file(
    data: Data,
    image: bytes = File(...),
):
    return {"postdata": len(image),
            "data": data.camera,
            }

if __name__ == "__main__":
    uvicorn.run(app)

client:

import requests
import cv2
import json
image = cv2.imread('/marti.jpg')
data2 = cv2.imencode(".jpg", image)[1]


payload = {"test1": "value_1", "test2": "value_2", "test3": "value_3"}
files = {
    'image': ('a.jpg', data2.tobytes(), 'image/jpeg', {'Expires': '0'})
}

res = requests.post("http://localhost:8000/uploadfile/",
                    files=files, data=payload)
print(res.content)
print(res.status_code, res.json())

the error i got:

422 Unprocessable Entity


What are your suggestions in the face of this situation?

Upvotes: 2

Views: 4912

Answers (2)

Mojtaba Arezoomand
Mojtaba Arezoomand

Reputation: 2380

You are getting Data in JSON body.

If you want to do it you should do:

@app.post("/uploadfile/")
async def create_file(
    test1: Optional[str] = Form(None),
    test2: Optional[str] = Form(None),
    test3: Optional[str] = Form(None),
    image: bytes = File(...),
):
    # Stuff here ...  

PS: [How to use pydantic model with form data]

Upvotes: 4

felipe
felipe

Reputation: 8055

You cannot. See documentation here:

You can declare multiple File and Form parameters in a path operation, but you can't also declare Body fields that you expect to receive as JSON, as the request will have the body encoded using multipart/form-data instead of application/json.

This is not a limitation of FastAPI, it's part of the HTTP protocol.

This is typically either resolved by expecting a Form as opposed to json (see this answer here), or by having two independent endpoints; one that uploads the photo and returns a matching ID, and another that leverages that ID to send the json data to.

Upvotes: 3

Related Questions