Let’s look at how to upload a file to a FastAPI route. It’s going to be easy!

For my app I need the Angular front-end to upload a PDF document to the FastAPI route defined at

@router.post("/", tags=["Documents"], response_model=schemas.IdResult)
@security.authorize(roles='admin,system,user')
async def upload_pdf(data:schemas.DocumentForm = Depends(schemas.DocumentForm.as_form),  db: Session = Depends(get_db), token_data:TokenData=Depends(security.get_token_data)):                
    #some code removed
    thistd = uuid.uuid1(0,0).hex                
    file_contents = data.pdf_file.file.read()       
    base_folder = os.path.join(Config.BASE_FILES_DIRECTORY, thistd)        
    os.makedirs(base_folder)
    file_name = f"{os.path.join(base_folder,thistd)}.pdf"
    with open(file_name,'wb') as f:                
        f.write(file_contents)                
    return schemas.IdResult(id=thistd, filename=data.pdf_file.filename)    

Here all I’m doing is generating a unique id for the uploaded file. The key here is the form used in the upload. The form the client uses is

class DocumentForm(BaseModel):
    title:str
    pdf_file:UploadFile    
    
    @classmethod
    def as_form(
            cls, title:str=Form(...),
                pdf_file:UploadFile = File(...)):
        return cls(title=title,pdf_file=pdf_file)    

This results in the following OpenAPI screen

upload

There you have it.