FastAPI (24) - explain File and upload File

Posted by killfall on Wed, 05 Jan 2022 10:12:03 +0100

FastAPI (24) - explain File and upload File



You can use the File provided by FastAPI to define the File to be uploaded by the client

Before learning File, you'd better learn Form:


Install Python multipart

To use File, you need to install this library first

pip install python-multipart



File inherits Form, so you can define the same metadata and additional validation as Form


Upload chestnuts for a single file

#!usr/bin/env python
# -*- coding:utf-8 _*-
# author: Little pineapple test notes
# blog:
# time: 2021/9/22 9:52 am
# file:
import uvicorn
from fastapi import FastAPI, File, UploadFile

app = FastAPI()

# The file parameter type is bytes"/files/")
async def create_file(file: bytes = File(...)):
    return {"file_size": len(file)}

# The file parameter type is UploadFile"/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    result = {
        "filename": file.filename,
        "content-type": file.content_type,
        "read": await
    return result

if __name__ == "__main__":"21_File:app", host="", port=8080, reload=True, debug=True)


a key

  • Because the methods provided by the UploadFile object are async asynchronous, await should be added when calling, such as await file Read() (async/await will be explained later)
  • When asynchronous methods are used, the FastAPI runs file methods in the thread pool and waits for them


Calling async method without await will report an error

    raise ValueError(errors)
ValueError: [TypeError("'coroutine' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
WARNING:  StatReload detected file change in ''. Reloading...


File: request result of bytes


File: request result of UploadFile


View Swagger API documentation

In this way, you can test the upload file function directly on the Swagger API document


file: bytes

  • The FastAPI will read the file and receive the file bytes
  • The whole content is stored in memory, which is more suitable for small files


file: UploadFile

The UploadFile of FastAPI directly inherits the UploadFile of Starlette, but adds some necessary parts to make it compatible with Pydantic and other parts of FastAPI


Advantages of UploadFile over bytes

  • The file stored in memory reaches the maximum size limit. After exceeding this limit, it will be stored in disk, which can handle large files, such as images, videos, large binary files, etc., without consuming all memory
  • Metadata can be obtained from the uploaded file
  • There is a file like async asynchronous interface
  • It exposes a Python SpooledTemporaryFile object that can be passed to other libraries that need files


UploadFile has the following properties

  • filename: str, the original file name uploaded, for example, myimage jpg
  • content_type: str, including content type (MIME type / media type), such as {image/jpeg
  • File: a SpooledTemporaryFile (an object similar to a file). This is the actual Python file, which can be passed directly to other functions or libraries that need "class file" objects


Uploadfill has the following async asynchronous methods

  • write(data): write data (str# or bytes) to a file
  • read(size): read the size (int) bytes / characters of the file
  • seek(offset): go to the byte position offset(int) in the file, such as await myfile Seek (0) will go to the beginning of the file
  • close(): close the file


Uploading multiple files of chestnuts

from typing import List"/files/")
async def create_files(files: List[bytes] = File(...)):
    return {"file_sizes": [len(file) for file in files]}"/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
    return {"filenames": [file.filename for file in files]}


Request result for correct parameter transmission


View Swagger API documentation


Topics: FastAPI