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:


import zipfile

file_list = ['E:\\files\image_1.jpg', 'E:\\files\image_2.jpg',
                 'E:\\files\image_3.jpg', 'E:\\files\image_4.jpg', 
                 'E:\\files\image_5.jpg'] 

with zipfile.ZipFile('final_archive.zip', 'w') as zip:
    for file in file_list:
        zip.write(file, compress_type=zipfile.ZIP_DEFLATED)

Here is the complete code to zip multiple files for download using FastAPI:


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

app = FastAPI()

@app.get("/files/download/{file_id}")
async def image_from_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', 
                 'E:\\files\image_5.jpg'] 
    return zipfiles(file_list)

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



if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=8005)
    print("running")    

The output of the above code is shown below:

Zip multiple files for download in Python using FastAPI