File Upload in FastAPI

FastAPI provides built-in support for handling file uploads.

File uploads are useful when users need to upload files such as:

  • Resumes
  • Images
  • PDFs
  • Documents
  • Other files

FastAPI provides UploadFile and File for handling uploaded files.

Import UploadFile and File

from fastapi import UploadFile, File

UploadFile represents the uploaded file, while File(...) tells FastAPI that the parameter should come from a file upload.

Create a File Upload Endpoint

from fastapi import UploadFile, File


@app.post("/upload")
async def upload_file(
    file: UploadFile = File(...)
):
    return {
        "filename": file.filename,
        "content_type": file.content_type
    }

Understanding the Code

UploadFile

file: UploadFile

UploadFile provides information and access to the uploaded file.

For example, it provides:

file.filename

to get the original filename.

It also provides:

file.content_type

to get the MIME type of the uploaded file.

File(...)

file: UploadFile = File(...)

File(...) tells FastAPI that the value should be received as an uploaded file.

The ... means the file is required.

Getting the Filename

file.filename

For example, if the user uploads:

resume.pdf

the value will be:

resume.pdf

Getting the Content Type

file.content_type

For a PDF file, the content type will typically be:

application/pdf

API Response

If the user uploads a file named resume.pdf, the API returns:

{
    "filename": "resume.pdf",
    "content_type": "application/pdf"
}

File Upload Flow

The basic flow is:

Client
   ↓
Upload File
   ↓
FastAPI Endpoint
   ↓
UploadFile
   ↓
Read File Information
   ↓
Return Response

Summary

In this topic, we learned:

  • FastAPI supports file uploads.
  • UploadFile is used to handle uploaded files.
  • File(...) defines a required file parameter.
  • file.filename provides the filename.
  • file.content_type provides the file’s MIME type.
  • File uploads can be handled using an asynchronous FastAPI endpoint.