FastAPI for AI Engineers - Part 8: Uploading Files with FastAPI
In the previous article, we learned how to secure our APIs using JWT Authentication and protect routes from unauthorized access. Now let's explore another feature used in almost every AI application-file uploads. If you've built applications like ChatGPT, document Q&A systems, resume analyzers, legal contract reviewers, or medical report analyzers, one thing is common across all of them: The user uploads a file. Without file uploads, there is nothing for the AI model to process. If you haven't read the previous article, check it out first to continue the series: Protecting routes with JWT Tokens Why Do We Need File Uploads? Consider some popular AI applications: - ChatGPT allows you to upload PDFs and images. - Resume analyzers require your resume. - Legal AI assistants analyze contracts. - Medical AI systems analyze lab reports. - RAG applications build knowledge bases from documents. The workflow usually looks like this: User โ โผ Upload File โ โผ FastAPI โ โผ Save / Read File โ โผ Process using AI FastAPI makes uploading files extremely simple. Installing Required Package FastAPI uses python-multipart to process uploaded files. Install it using: pip install python-multipart Your First File Upload API FastAPI provides two important classes: File UploadFile Let's import them. from fastapi import FastAPI, File, UploadFile app = FastAPI() Creating the Upload Endpoint @app.post("/upload") def upload_file(file: UploadFile): return { "filename": file.filename } Run the application. Open Swagger UI. Click POST /upload. You'll notice FastAPI automatically provides a file picker. Upload a file. Response: { "filename": "resume.pdf" } Our API successfully received the uploaded file. Understanding UploadFile You might wonder: Why didn't we simply use a string or bytes? FastAPI provides the UploadFile class because it contains useful information about the uploaded file. Some commonly used attributes are: file.filename Returns: resume.pdf file.content_type Returns: application/pdf await file.read() Reads the file contents. These attributes become extremely useful when building AI applications. Reading File Contents Suppose we want to know how many bytes were uploaded. @app.post("/upload") async def upload_file(file: UploadFile): contents = await file.read() return { "filename": file.filename, "size": len(contents) } Example response: { "filename": "contract.pdf", "size": 254321 } Notice that we changed the function to: async def This is because file.read() is an asynchronous operation. Saving Uploaded Files In many applications, we don't just read the file. We save it for later processing. @app.post("/upload") async def upload_file(file: UploadFile): contents = await file.read() with open(file.filename, "wb") as f: f.write(contents) return { "message": "File uploaded successfully." } contents = await file.read() Reads the uploaded file into memory. with open(file.filename, "wb") Creates a new file. The "wb" mode means: - w โ Write - b โ Binary mode Binary mode is important because PDFs, images, Word documents, and many other files are not plain text. f.write(contents) Writes the uploaded data to disk. AI Workflow Example Suppose a user uploads a legal contract. contract.pdf โ โผ FastAPI Upload Endpoint โ โผ Save PDF โ โผ Extract Text โ โผ Create Embeddings โ โผ Store in Vector Database โ โผ Ask Questions This is the same workflow followed by many Retrieval-Augmented Generation (RAG) applications. Similarly, Resume Analyzer: Resume.pdf โ โผ Extract Text โ โผ Skill Extraction โ โผ ATS Score Medical Report Analyzer: Blood_Report.pdf โ โผ OCR / Text Extraction โ โผ LLM Analysis โ โผ Health Summary File uploads are the entry point for almost every document-based AI application. UploadFile vs bytes FastAPI also allows uploading files as raw bytes. @app.post("/upload") async def upload(file: bytes = File()): return { "size": len(file) } Although this works, it is rarely used for large files. UploadFile is generally preferred because: - It provides metadata such as filename and content type. - It is optimized for larger uploads. - It is more memory efficient. For most production applications, UploadFile is the recommended choice. Complete Example from fastapi import FastAPI, UploadFile app = FastAPI() @app.post("/upload") async def upload_file(file: UploadFile): contents = await file.read() with open(file.filename, "wb") as f: f.write(contents) return { "filename": file.filename, "content_type": file.content_type, "size": len(contents), "message": "Upload Successful" } Workflow Recap User Uploads File โ โผ FastAPI Receives Upload โ โผ UploadFile Object Created โ โผ Read File โ โผ Save File โ โผ AI Processing Begins Final Thoughts Uploading files is one of the most important capabilities of modern AI backends. Whether you're building a chatbot over PDFs, a resume analyzer, a legal contract assistant, or a medical report analyzer, every application begins with accepting user files. Today we learned how to: - Upload files using FastAPI - Understand the UploadFile object - Read uploaded files - Save files locally - Understand where file uploads fit into AI workflows It's been some time since I've uploaded. We will continue with our FastAPI series in the upcoming posts. Top comments (1) Do comment down any doubts you have, or which is the next topic you would like me to take?
Comments
No comments yet. Start the discussion.