1

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

JPG
  • 82,442
  • 19
  • 127
  • 206
user_12
  • 1,778
  • 7
  • 31
  • 72
  • Does this answer your question? [How to add both file and JSON body in a FastAPI POST request?](https://stackoverflow.com/questions/65504438/how-to-add-both-file-and-json-body-in-a-fastapi-post-request) – Chris Mar 18 '23 at 07:58

1 Answers1

2

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}
JPG
  • 82,442
  • 19
  • 127
  • 206
  • Now, when I pass inputs through postman, I am getting an error with industry, It is returning No, please check the screenshot, in the predict function I wrote a if condition where if industry is None return No – user_12 Oct 06 '20 at 20:21
  • 1
    @user_12 Updated the answer – JPG Oct 06 '20 at 20:30
  • 1
    what does that `...` represent – user_12 Oct 07 '20 at 07:47
  • 2
    It is the [Ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis). In FastAPI, we can set a parameter/argument as [***required***](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#make-it-required) by using this `...` value @user_12 – JPG Oct 07 '20 at 07:52