How to return and download Excel file using FastAPI?

You could set the Content-Disposition header using the attachment parameter, indicating to the browser that the file should be downloaded, as described in the answers here and here. Swagger UI will provide a Download file link for you to download the file, as soon as you execute the request.

headers = {'Content-Disposition': 'attachment; filename="Book.xlsx"'}
return FileResponse(excel_file_path, headers=headers)

To have the file viewed in the browser, one can use the inline, instead of attachment, parameter in the Content-Disposition header, as explained in the linked answers earlier. However, for the browser to be able to display the Excel file, one should set the correct media_type in the FileResponse (for Excel files see here), as well as .xlsx (or .xls) must be a known file extension to the browser (this is usually achieved through browser extensions/plug-ins).

Leave a Comment