2

I have a function like this,

async def predict(static: str = Form(...), file: UploadFile = File(...)):
    return something

I have two parameters here, static and file and static is a string, file is buffer of uploaded file.

Now, is there a way to assign multiple types to one parameter, i.e., I want to make file parameter take either upload file or just string

1 Answer 1

3

Use Union type annotation

from fastapi import FastAPI, UploadFile, Form, File
from typing import Union

app = FastAPI()


@app.post(path="/")
async def predict(
        static: str = Form(...),
        file: Union[UploadFile, str] = File(...)
):
    return {
        "received_static": static,
        "received_file": file if isinstance(file, str) else file.filename
    }

AFAIK, OpenAPI schema doesn't support this config since it doesn't support multiple types. So, better to define multiple parameters to handle things differently. Also, IMHO, it is the better way

from fastapi import FastAPI, UploadFile, Form, File

app = FastAPI()


@app.post(path="/")
async def predict(
        static: str = Form(...),
        file: UploadFile = File(None),  # making optional
        file_str: str = Form(None)  # making optional
):
    return {
        "received_static": static,
        "received_file": file.filename if file else None,
        "received_file_str": file_str if file_str else ''
    }
Sign up to request clarification or add additional context in comments.

1 Comment

It is a bit silly to produce reasonable looking code that doesn't work. With fastapi it apparently tries to instantiate the parameter, and it doesn't go into Unions before trying to do so. That means you get the dreaded TypeError: Cannot instantiate typing.Union error. You should un-fastapi the first example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.