Implementing JWT authentication and authorization in FastAPI

Let’s look at how to implement authentication and authorization in FastAPI. I’m going to assume you use VS Code or an IDE that’s capable of automatically resolving the required imports. There’s already a page in the FastAPIdocumentation about authentication but I’m going to extend that information to show you how to add authorization using JWT where your roles sit in a database. And it’s going to be so easy. When we’re all done we’ll be protecting routes like this @router....

Upload a file to a FastAPI route

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....