Uploading files lets users send documents or images to your app. It helps your app receive data like photos or reports.
File upload (single file) in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/uploadfile/") async def upload_file(file: UploadFile = File(...)): contents = await file.read() return {"filename": file.filename, "content_type": file.content_type}
UploadFile is used to handle the uploaded file efficiently.
File(...) marks the parameter as required for upload.
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/uploadfile/") async def upload_file(file: UploadFile = File(...)): return {"filename": file.filename}
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/uploadfile/") async def upload_file(file: UploadFile = File(...)): contents = await file.read() size = len(contents) return {"filename": file.filename, "size_bytes": size}
This complete FastAPI app accepts one uploaded file. It reads the file content to get its size and returns the file name, type, and size as JSON.
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/uploadfile/") async def upload_file(file: UploadFile = File(...)): contents = await file.read() return { "filename": file.filename, "content_type": file.content_type, "size_bytes": len(contents) }
Use UploadFile for better performance with large files instead of reading all bytes at once.
Always check file.content_type to validate file types for security.
Remember to handle exceptions for missing or invalid files.
Use UploadFile and File(...) to accept single file uploads in FastAPI.
Read file content asynchronously with await file.read() to get file data.
Return useful info like filename, content type, and size to confirm upload success.
Practice
Solution
Step 1: Understand FastAPI file upload types
FastAPI usesUploadFileto handle file uploads efficiently.Step 2: Identify single file upload parameter
For a single file, the parameter type isUploadFile, not a list or primitive type.Final Answer:
<code>UploadFile</code> -> Option CQuick Check:
Single file upload uses UploadFile [OK]
- Using str or int instead of UploadFile
- Using List[UploadFile] for single file
- Not importing UploadFile from fastapi
Solution
Step 1: Check parameter declaration for file upload
FastAPI requiresFile(...)to mark the parameter as a file upload.Step 2: Match type with File marker
The type must beUploadFilecombined withFile(...)for single file upload.Final Answer:
file: UploadFile = File(...) -> Option DQuick Check:
UploadFile with File(...) is correct syntax [OK]
- Omitting File(...) marker
- Using str or bytes instead of UploadFile
- Not assigning default File(...)
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
@app.post('/upload')
async def upload(file: UploadFile = File(...)):
content = await file.read()
return {'filename': file.filename, 'content_type': file.content_type, 'size': len(content)}Solution
Step 1: Read file content asynchronously
The code usesawait file.read()to get the file bytes, so content length is 5 for 'hello'.Step 2: Return file info correctly
Filename is 'test.txt', content type is 'text/plain' (default for .txt), size is length of content (5).Final Answer:
{'filename': 'test.txt', 'content_type': 'text/plain', 'size': 5} -> Option AQuick Check:
File info returned matches uploaded file [OK]
- Not awaiting file.read() causing empty content
- Assuming wrong content_type
- Returning filename as empty string
from fastapi import FastAPI, UploadFile
app = FastAPI()
@app.post('/upload')
def upload(file: UploadFile = File(...)):
content = file.read()
return {'filename': file.filename, 'size': len(content)}Solution
Step 1: Check imports and function signature
The code misses importingFileand the function is not async but callsfile.read()which is async.Step 2: Identify async usage and await
To read file content, function must be async and useawait file.read().Final Answer:
All of the above -> Option BQuick Check:
Missing import, async, and await cause errors [OK]
- Forgetting to import File
- Using sync function with async file.read()
- Not awaiting file.read()
Solution
Step 1: Use async function with UploadFile and File(...)
Correct signature is async def with parameterfile: UploadFile = File(...).Step 2: Read file content and decode first 10 bytes
Read content withawait file.read(), then slice first 10 bytes and decode to UTF-8 string.Step 3: Return filename, content_type, and preview string
Return dictionary with correct file info and preview snippet.Final Answer:
Option A code snippet -> Option AQuick Check:
Async read, slice, decode first 10 bytes [OK]
- Using sync function without await
- Decoding entire content before slicing
- Using bytes type instead of UploadFile
