DEV Community

Free Python Code
Free Python Code

Posted on

Create a file uploader API using FastAPI and Python

Hi 🙂🖐

Welcome in a new post, today i will share with you how to Create a file uploader API using FastAPI and Python.

Step 1

Import modules

from fastapi import FastAPI
from fastapi import File, UploadFile
from fastapi.responses import FileResponse
from secrets import token_hex

import shutil
import os
Enter fullscreen mode Exit fullscreen mode

Step 2

Create route for uploading files

app = FastAPI()

@app.get('/')
def home():
    return {'msg': 'Welcome In The API'}


@app.post('/upload')
def upload(file : UploadFile = File(...)):
    file_id = token_hex(20)
    full_path = f'files/{file_id}---{file.filename}'
    with open(full_path, 'wb') as buffer:
        shutil.copyfileobj(file.file, buffer)

    return {
        'msg': 'Done', 
        'file_link': f'http://127.0.0.1:8000/{full_path}'}

Enter fullscreen mode Exit fullscreen mode

Upload file to the API

import requests

files = {'file': open('test.png', 'rb')}

res = requests.post('http://127.0.0.1:8000/upload', files=files)
print(res.json())
Enter fullscreen mode Exit fullscreen mode

result

{'msg': 'Done', 'file_link': 'http://127.0.0.1:8000/files/0a89f439b0eca2e4c1a586ee5dd0807beada3fd1---test.png'}
Enter fullscreen mode Exit fullscreen mode

Now we need to create route to get this file

@app.get('/files/{file_name}')
def get_file(file_name : str):
    for f_name in os.listdir('files'):
        if f_name == file_name:
            return FileResponse(f'files/{file_name}')

    return {'msg': 'File not found :('}
Enter fullscreen mode Exit fullscreen mode

result

Image description

full code


from fastapi import FastAPI
from fastapi import File, UploadFile
from fastapi.responses import FileResponse
from secrets import token_hex

import shutil
import os

app = FastAPI()

@app.get('/')
def home():
    return {'msg': 'Welcome In The API'}


@app.post('/upload')
def upload(file : UploadFile = File(...)):
    file_id = token_hex(20)
    full_path = f'files/{file_id}---{file.filename}'
    with open(full_path, 'wb') as buffer:
        shutil.copyfileobj(file.file, buffer)

    return {
        'msg': 'Done', 
        'file_link': f'http://127.0.0.1:8000/{full_path}'}


@app.get('/files/{file_name}')
def get_file(file_name : str):
    for f_name in os.listdir('files'):
        if f_name == file_name:
            return FileResponse(f'files/{file_name}')

    return {'msg': 'File not found :('}
Enter fullscreen mode Exit fullscreen mode

Now we're done 🤗

Don't forget to like and follow 🙂

Support me on PayPal 🤗
https://www.paypal.com/paypalme/amr396

Top comments (0)