DEV Community

Cover image for How to create server of files with FastAPI
Nelson Hernández
Nelson Hernández

Posted on • Edited on

12 5

How to create server of files with FastAPI

In this example I will show you how to upload, download, delete and obtain files with FastAPI

Upload files by Form Data using FastAPI

In the following code we define the file field, it is there where we will receive the file by Form Data

from fastapi import FastAPI, UploadFile, File
app = FastAPI()

@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    with open(file.filename, 'wb') as image:
        content = await file.read()
        image.write(content)
        image.close()
    return JSONResponse(content={"filename": file.filename},
status_code=200)
Enter fullscreen mode Exit fullscreen mode

Download files using FastAPI

from fastapi import FastAPI
from os import getcwd
from fastapi.responses import FileResponse
app = FastAPI()

@router.get("/download/{name_file}")
def download_file(name_file: str):
    return FileResponse(path=getcwd() + "/" + name_file, media_type='application/octet-stream', filename=name_file)
Enter fullscreen mode Exit fullscreen mode

Get files using FastAPI

from fastapi import FastAPI
from os import getcwd
from fastapi.responses import FileResponse

app = FastAPI()

@router.get("/file/{name_file}")
def get_file(name_file: str):
    return FileResponse(path=getcwd() + "/" + name_file)
Enter fullscreen mode Exit fullscreen mode

Delete files using FastAPI

from fastapi import FastAPI
from os import getcwd, remove
from fastapi.responses import JSONResponse

app = FastAPI()

@router.delete("/delete/file/{name_file}")
def delete_file(name_file: str):
    try:
        remove(getcwd() + "/" + name_file)
        return JSONResponse(content={
            "removed": True
            }, status_code=200)   
    except FileNotFoundError:
        return JSONResponse(content={
            "removed": False,
            "error_message": "File not found"
        }, status_code=404)
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay