File Handling in FastAPI

Building APIs requires careful file handling, which is a critical component of web development. We will look at how FastAPI makes file uploading, downloading, and serving easier in this blog post. FastAPI provides convenient tools for handling files of various sizes and types, making it an excellent choice for building robust APIs.

Uploading Files with FastAPI

File() for Small Files:

FastAPI provides the File() function for handling direct file uploads, suitable for relatively small files. Let’s look at an example where we upload a small file and retrieve its size.

from fastapi import FastAPI, File

app = FastAPI()

@app.post(“/small”)

async def upload_small_file(small_file: bytes = File(…)):

    return f”file size: {len(small_file)}”

In this example, the upload_small_file endpoint accepts a small_file parameter of type bytes, representing the uploaded file. The function returns the size of the file.

Example Test with HTTPie:

bash

$ http -f -b POST http://localhost:8000/small small_file@1KB.bin

# Output: “file size: 1000”

UploadFile for Large Files:

For larger files, it’s recommended to use UploadFile. This creates a SpooledTemporaryFile object, minimizing memory usage during the upload process.

Python

from fastapi import FastAPI, UploadFile

app = FastAPI()

@app.post(“/big”)

async def upload_big_file(big_file: UploadFile = File(…)):

    return f”file size: {big_file.size}, name: {big_file.filename}”

In this example, the upload_big_file endpoint takes an UploadFile parameter, providing information about the uploaded file. The function returns the size and name of the file.

Example Test with HTTPie:

Bash

$ http -f -b POST http://localhost:8000/big big_file@1GB.bin

# Output: “file size: 1000000000, name: 1GB.bin”

Downloading Files with FastAPI

File Response for Small Files:

FastAPI offers FileResponse for downloading small files in one go. Let’s create an endpoint to download a small file.

Python

from fastapi import FastAPI, FileResponse

app = FastAPI()

 

@app.get(“/small/{name}”)

async def download_small_file(name):

    return FileResponse(name)

This endpoint returns a FileResponse for the requested file, allowing the client to download it in its entirety.

Example Test with HTTPie:

Bash

$ http -b http://localhost:8000/small/1KB.bin

# Output: Binary data not shown in the terminal

StreamingResponse for Large Files:

When dealing with large files, it’s more efficient to use StreamingResponse to download files in chunks. Here’s an example:

Python

from fastapi import FastAPI, StreamingResponse

from pathlib import Path

app = FastAPI()

def gen_file(path: str):

    with open(file=path, mode=”rb”) as file:

        yield file.read()

@app.get(“/download_big/{name}”)

async def download_big_file(name:str):

    gen_expr = gen_file(file_path=path)

    response = StreamingResponse(content=gen_expr, status_code=200)

    return response

In this example, the download_big_file endpoint uses a generator function to read and yield file chunks, which are then sent as a StreamingResponse.

Example Test with HTTPie:

bash

$ http -b http://localhost:8000/download_big/1GB.bin | wc

# Output: 1000000000

Serving Static Files with FastAPI

FastAPI also supports serving static files using StaticFiles. Let’s create a simple setup to serve files from a directory.

Python

from fastapi import FastAPI

from fastapi.staticfiles import StaticFiles

from pathlib import Path

app = FastAPI()

top = Path(__file__).resolve().parent

app.mount(“/static”, StaticFiles(directory=f”{top}/static”, html=True), name=”free”)

This configuration serves files from the “static” directory and returns an index.html file if present.

Example Test for Static Files:

Bash

$ http -b localhost:8000/static/abc.txt

# Output: abc 🙂

FastAPI is a strong option for developing APIs that include file uploads, downloads, and static file serving because of its file handling capabilities. Regardless of the size of the file, FastAPI offers sophisticated solutions that improve the overall developer experience. Including these functionalities in your FastAPI projects will definitely make file-related tasks easier.

Visited 1 times, 1 visit(s) today