Return Excel/CSV File as a Response Stream FastAPI

Tags : FastAPI / Pandas


Code base to return excel/csv file using Streaming Response in FastAPI

Returning an excel file through Streaming Response

  1. Writing data to an excel stream from dataframe

    from io import BytesIO

    stream = BytesIO()
    df.to_excel(stream, index=False, engine="openpyxl") # Note: need to install openpyxl

  2. Return a Streaming Response Object from FastAPI responses module

    ```
    from fastapi.responses import StreamingResponse

    response = StreamingResponse( iter([stream.getvalue()]), media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", headers = { 'Content-Disposition': 'attachment;filename=sample_filename.xlsx',
    'Access-Control-Expose-Headers': 'Content-Disposition' #this is optional
    })
    return response
    ```

Returning an csv file through Streaming Response

  1. Writing data to an csv stream from dataframe

    from io import StringIO

    stream = StringIO()
    df.to_csv(stream, index=False)

  2. Return a Streaming Response Object from FastAPI responses module

    ```
    from fastapi.responses import StreamingResponse

    response = StreamingResponse(
    iter([stream.getvalue()]), media_type="text/csv",
    headers={
    'Content-Disposition': 'attachment;filename=sample_filename.csv', 'Access-Control-Expose-Headers': 'Content-Disposition' # this is optional
    })
    return response ```