Get and Return PDF File Using FAST-API

Tiempo de lectura: < 1 minuto

Reading time: < 1 minute

Hello, today we are going to see how we can retrieve a saved PDF file and return it using Fast API with Python.

We go to our routes file and add the necessary dependencies (in addition to those of Fast API):

import os
from fastapi.responses import FileResponse

Now we are going to create our Route, which will be a GET that will return the PDF file.

@app.get("/get_pdf", status_code=status.HTTP_200_OK)
def get_convenio_pdf() -> FileResponse:
   

    # Having the filename, return the file inside the pdf folder
    file_name = "file_name_to_return"
    pdf_folder = "pdf"
    pdf = os.path.join(pdf_folder, file_name)

    # Check if the file exists
    if not os.path.exists(pdf):
        return {"error": "The file does not exist"}
    # Return the pdf file from the /pdf/ folder
    return FileResponse(pdf, media_type='application/pdf', filename=file_name)

In this simple function, when we invoke /get_pdf, we obtain the PDF from the /pdf/file.pdf folder.

We specify the name in the variable file_name, but we can pass the name as a parameter, for example, or we can also store it in the database and link it by ID.

Finally, it returns it using a FileResponse object, which will return a BLOB of the PDF.

Leave a Comment