File Uploads with FastAPI

Writing our file upload endpoint

Want more?

This lesson for enrolled students only. Join the course to unlock it!

You can see the code changes implemented in this lecture below.

If you have purchased the course in a different platform, you still have access to the code changes per lecture here on Teclado. The lecture video and lecture notes remain locked.
Join course for $30

New files

storeapi/routers/upload.py
import logging
import tempfile

import aiofiles
from fastapi import APIRouter, HTTPException, UploadFile, status
from storeapi.libs.b2 import b2_upload_file

logger = logging.getLogger(__name__)

router = APIRouter()

CHUNK_SIZE = 1024 * 1024


@router.post("/upload", status_code=201)
async def upload_file(file: UploadFile):
    try:
        with tempfile.NamedTemporaryFile() as temp_file:
            filename = temp_file.name
            logger.info(f"Saving uploaded file temporarily to {filename}")
            async with aiofiles.open(filename, "wb") as f:
                while chunk := await file.read(CHUNK_SIZE):
                    await f.write(chunk)

            file_url = b2_upload_file(local_file=filename, file_name=file.filename)
    except Exception:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="There was an error uploading the file",
        )

    return {"detail": f"Successfully uploaded {file.filename}", "file_url": file_url}

Modified files

storeapi/main.py
--- 
+++ 
@@ -8,6 +8,7 @@
 from storeapi.database import database
 from storeapi.logging_conf import configure_logging
 from storeapi.routers.post import router as post_router
+from storeapi.routers.upload import router as upload_router
 from storeapi.routers.user import router as user_router

 logger = logging.getLogger(__name__)
@@ -25,10 +26,11 @@
 app.add_middleware(CorrelationIdMiddleware)

 app.include_router(post_router)
+app.include_router(upload_router)
 app.include_router(user_router)


 @app.exception_handler(HTTPException)
 async def http_exception_handle_logging(request, exc):
     logger.error(f"HTTPException: {exc.status_code} {exc.detail}")
-    return await http_exception_handler(request, exc)+    return await http_exception_handler(request, exc)