Home > Mobile >  How to return a PDF file from in-memory buffer using FastAPI?
How to return a PDF file from in-memory buffer using FastAPI?

Time:09-03

I want to get a PDF file from s3 and then return it to the frontend from FastAPI backend.

This is my code:

@router.post("/pdf_document")
def get_pdf(document : PDFRequest) :
    s3 = boto3.client('s3')
    file=document.name
    f=io.BytesIO()
    s3.download_fileobj('adm2yearsdatapdf', file,f)
    return StreamingResponse(f, media_type="application/pdf")

This API returns 200 status code, but it does not return the PDF file as a response.

CodePudding user response:

As the entire file data are already loaded into memory, it makes little sense to use StreamingResponse. You should instead use Response, by passing the file bytes (use BytesIO.getvalue() to get the bytes containing the entire contents of the buffer), defining the media_type, as well as setting the Content-Disposition header, so that the file can be either viewed in the browser or downloaded to the user's device. For more details have a look at this, as well as this and this answer.

from fastapi import Response

@app.get("/pdf")
def get_pdf():
    ...
    buffer = io.BytesIO()
    ...
    headers = {'Content-Disposition': 'attachment; filename="out.pdf"'}
    return Response(buffer.getvalue(), headers=headers, media_type='application/pdf')

To have the PDF file viewed in the borwser rather than downloaded, use:

headers = {'Content-Disposition': 'inline; filename="out.pdf"'}
  • Related