Skip to content

How can a parameter name support multiple variable types? #3751

@xxddccaa

Description

@xxddccaa

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

# -*- coding:utf-8 -*-
import traceback
from typing import Optional
import uvicorn
from fastapi import FastAPI, File, Form, UploadFile

app = FastAPI()


@app.post("/filesper/")
def filesper(
        file: Optional[UploadFile, bytes, str] = Optional[File(...), Form(...)],
):
    try:
        if file:
            return 1
    except:
        traceback.print_exc()
        return -1


if __name__ == '__main__':
    uvicorn.run('testfastapi:app', host='0.0.0.0', port=8001, reload=False, debug=False, workers=1)

Description

hello!
How can a parameter variable name support multiple types?
In the program,file: Optional[UploadFile, bytes, str] = Optional[File(...), Form(...)],this program is my imagination,I want file parameter can be anything that I need, isinstance() can be used to distinguish detail types.
I don't think it can succeed, but I want to know why.
thank you!

Operating System

Linux

Operating System Details

CentOS 7

FastAPI Version

0.68.0

Python Version

Additional Context

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions