How to Zip Mulitiple Files in Python for Download using FastAPI

Python provides zipfile, a built-in module to zip files. Zipping files also help to reduce the size of the files.

ZIP is a file format that compresses data without reducing the quality. The original data can be completely rebuilt from the compressed data.

In this example tutorial, we will show you how to write code for zipping multiple files in Python for download using FastAPI.

Here is a code to zip multiple files in Python:

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import uvicorn
import zipfile
from io import BytesIO

app = FastAPI()

async def download_image_by_id(file_id: int):
    # Get filenames from the database
    file_list = ['E:\\files\image_1.jpg', 'E:\\files\image_2.jpg',
                 'E:\\files\image_3.jpg', 'E:\\files\image_4.jpg',
    return zipfiles(file_list)

def zipfiles(file_list):
    io = BytesIO()
    zip_sub_dir = "final_archive"
    zip_filename = "" % zip_sub_dir
    with zipfile.ZipFile(io, mode='w', compression=zipfile.ZIP_DEFLATED) as zip:
        for fpath in file_list:
        #close zip
    return StreamingResponse(
        headers = { "Content-Disposition":f"attachment;filename=%s" % zip_filename}

if __name__ == '__main__':, host='', port=8005)