Reputation: 5791
I would like to get image via post request and then read it. I'm trying to do is this way:
import numpy as np
from PIL import Image
from fastapi import FastAPI, File, UploadFile, HTTPException, Depends
app = FastAPI()
@app.post("/predict_image")
@logger.catch
def predict_image(predict_image: UploadFile = File(...)):
logger.info('predict_image POST request performed')
try:
pil_image = np.array(Image.open(predict_image.file))
except:
raise HTTPException(
status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail="Unable to process file"
)
pred = pil_image.shape
logger.info('predict_image POST request performed, shape {}'.format(pred))
return {'input_shape': pred}
Calling post request returns INFO: 127.0.0.1:59364 - "POST /predict_image HTTP/1.1" 400 Bad Request
How to fix it?
UPD:
Example from official tutorial return same exception:
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
Upvotes: 1
Views: 4137
Reputation: 5791
Fixed this way:
@app.post("/predict_image/")
@logger.catch
def make_inference(file: bytes = File(...)):
try:
pil_image = np.array(Image.open(BytesIO(file)))
except:
raise HTTPException(
status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail="Unable to process file"
)
Upvotes: 0
Reputation: 824
You probably need to install python-multipart.
Just:
pip install python-multipart
Upvotes: 5