Python - FastAPI - Optional option for an UploadFile

See original GitHub issue

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

from typing import Optional
from fastapi import FastAPI, UploadFile, File

app = FastAPI()

@app.get("/")
def root():
    pass

@app.post("/OptionOne")
def pdf_foo1(file: Optional[UploadFile] = None):
    print(file.filename)

@app.post("/OptionTwo")
def pdf_foo2(file: Optional[UploadFile] = File(None)):
    print(file.filename)

@app.post("/OptionThree")
def pdf_foo3(file: UploadFile = File(None)):
    print(file.filename)

@app.post("/OptionFour")
def pdf_foo4(file: UploadFile = None):
    print(file.filename)

@app.post("/OptionFive")
def pdf_foo5(file: bytes = File(None)):
    print(file)

Description

Short Summary

I am trying to do what I think is a simple thing but no internet solution has helped me so far, and I didn’t find anything helpful yet in the issues.


The desired solution:

A route (function) that will accept an UploadFile but that will be optional, the user will not be have to provide it.

Current Case:

In the code there are 5 different cases I tried, all of them are not working as follows: Cases 1, 3 Gives an ‘ValueError: Value not declarable with JSON Schema’ Cases 2, 4 Acts like it’s not always must:

  • It will boot up and start working, but when I try to send a request (for example in the docs swagger) it will gives me a 422 error and will say it excepts data named “file” (in this case) Case 5 Gives a different error (up until now I saw 3 different ones) but anyway using bytes is not the solution I’m looking for.

Operating System

Linux, Windows

Operating System Details

Im developing on a windows server, and publish on a Linux webapp (Azure)

FastAPI Version

0.70.1

Python Version

3.8.2

Additional Context

I’m testing it with Swagger (Locally and Webapp) and also using the API links in a different program ( If I missed anything, or there is anything else you need to know in order to resolve this issue, please comment and I will update the data accordingly within 12 hours max [Not including Friday and Saturday] )

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:22

github_iconTop GitHub Comments

8reactions
LidorPrototypecommented, Mar 24, 2022

Hey, if you will look at the options I wrote there, there is an option like that one in the docs (OptionOne and part of OptionFive but OptionFive is not good for me anyway)

1reaction
jd-solankicommented, Mar 31, 2022

I assume you want to process the file if uploaded and do nothing or skip the processing if file is not uploaded.

Please try below code:

import aiofiles

from fastapi import FastAPI, File, UploadFile

app = FastAPI()


@app.post("/")
async def read_root(
    uploaded_file: UploadFile = File(None),
):
    r = {"file_status": "no file is provided"}
    if uploaded_file:
        async with aiofiles.open(f"{uploaded_file.filename}", "wb") as out_file:
            content = await uploaded_file.read()  # async read
            await out_file.write(content)

        r["file_status"] = "File is uploaded"
    return r

requirements.txt

irements.txt 
aiofiles==0.8.0
anyio==3.5.0
asgiref==3.5.0
click==8.1.1
fastapi==0.75.0
h11==0.13.0
httptools==0.4.0
idna==3.3
pydantic==1.9.0
python-dotenv==0.20.0
python-multipart==0.0.5
PyYAML==6.0
six==1.16.0
sniffio==1.2.0
starlette==0.17.1
typing_extensions==4.1.1
uvicorn==0.17.6
uvloop==0.16.0
watchgod==0.8.1
websockets==10.2

In here if you upload the file then app will save it in your machine and if you don’t upload a file then it will return “no file is provided”.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Request Files - FastAPI
Optional File Upload¶. You can make a file optional by using standard type annotations and setting a default value of None : Python...
Read more >
How to set the file multiple file upload field as an Optional field ...
I am required to get the multiple file upload field as an Optional one The documentation has the above mentioned code but it...
Read more >
Forms and File Uploads with FastAPI and Jinja2 - YouTube
This video covers how to set handle forms and file uploads in FastAPI using Jinja2 templatesThe example code for this project can be...
Read more >
Communicate via JSON payload and upload files in FastAPI!
app = FastAPI()#Base model class Options (BaseModel): FileName: str FileDesc: str = “Upload for demonstration” FileType: Optional[str].
Read more >
File Upload - Swagger
paths: /upload: post: summary: Uploads a file. ... parameters: - in: formData; name: upfile; type: file; required: true; description: The file to upload....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found