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
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}'}
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())
result
{'msg': 'Done', 'file_link': 'http://127.0.0.1:8000/files/0a89f439b0eca2e4c1a586ee5dd0807beada3fd1---test.png'}
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 :('}
result
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 :('}
Now we're done 🤗
Don't forget to like and follow 🙂
Support me on PayPal 🤗
https://www.paypal.com/paypalme/amr396
Top comments (0)