File operations are common in FastAPI apps because users often upload files, and the app needs to save or read these files to work with the data.
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/upload") async def upload_file(file: UploadFile = File(...)): contents = await file.read() with open(f"uploads/{file.filename}", "wb") as f: f.write(contents) return {"filename": file.filename}
The code reads the uploaded file and writes it to a folder on the server, saving it for future use.
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/upload") async def upload_file(file: UploadFile = File(...)): contents = file.read() with open(f"uploads/{file.filename}", "wb") as f: f.write(contents) return {"filename": file.filename}
The method file.read() is asynchronous and must be awaited with 'await'. Calling it without await returns a coroutine object, causing a TypeError when writing.
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/upload") async def upload_file(file: UploadFile = File(...)): contents = await file.read() with open(f"uploads/{file.filename}", "wb") as f: f.write(contents) return {"filename": file.filename, "size": len(contents)}
The endpoint returns a JSON with the uploaded file's name and the byte size of its content.
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/upload") def upload_file(file: UploadFile = File(...)): contents = file.file.read() with open(f"uploads/{file.filename}", "wb") as f: f.write(contents) return {"filename": file.filename}
UploadFile.file.read() is a blocking call, but UploadFile is designed to be used asynchronously. The function should be async and use await file.read() for proper file handling.
