How to add multiple body params with fileupload in FastAPI?

6.3k views Asked by At

I have a machine learning model deployed using FastAPI, but the issue is I need the model to take two-body parameters

app = FastAPI()

class Inputs(BaseModel):
    industry: str = None
    file: UploadFile = File(...)

@app.post("/predict")
async def predict(inputs: Inputs):
    # params
    industry = inputs.industry
    file = inputs.file
    ### some code ###
    return predicted value

When I tried to send the input parameters I am getting an error in postman, please see the pic below,

enter image description here

enter image description here

1

There are 1 answers

4
JPG On BEST ANSWER

From the FastAPI discussion thread--(#657)

if you are receiving JSON data, with application/json, use normal Pydantic models.

This would be the most common way to communicate with an API.

If you are receiving a raw file, e.g. a picture or PDF file to store it in the server, then use UploadFile, it will be sent as form data (multipart/form-data).

If you need to receive some type of structured content that is not JSON but you want to validate in some way, for example, an Excel file, you would still have to upload it using UploadFile and do all the necessary validations in your code. You could use Pydantic in your own code for your validations, but there's no way for FastAPI to do it for you in that case.

So, in your case, the router should be as,

from fastapi import FastAPI, File, UploadFile, Form

app = FastAPI()


@app.post("/predict")
async def predict(
        industry: str = Form(...),
        file: UploadFile = File(...)
):
    # rest of your logic
    return {"industry": industry, "filename": file.filename}