Upload PDF File Using FAST-API

Tiempo de lectura: < 1 minuto

Reading time: < 1 minute

Hello, today we are going to see how we can upload a PDF file using FAST-API.

The first thing we need to do is install python multipart:

install python-multipart

Once installed, we need to go to our routes file and import this:

import shutil

Now we create this Route:

@app.post("/_pdf", status_code=status.HTTP_201_CREATED)
def subir_pdf(pdf_file: UploadFile = File(...)):
    upload_folder = "pdf"
   
    # Current date for the file name + company id
    # Get current date
    now = datetime.now()
    dt_string = now.strftime("%d_%m_%Y_%H_%M_%S")

    file_name = dt_string + ".pdf"
    with open(f"{upload_folder}/{file_name}", "wb") as buffer:
        shutil.copyfileobj(pdf_file.file, buffer)

    return {"filename": file_name}

This function allows you to upload a PDF and store it in a folder called PDF. It also stores it with the current date and time.

The result in Swagger is this:

Leave a Comment