How to upload file in FastAPI and Python.

Free Python Code - Sep 5 '23 - - Dev Community

Hi 🙂🖐

In this post, I will share with you how to upload file in FastAPI and Python in easy way.

step 1

You need to install fastapi pip install fastapi
and pip install python-multipart

step 2

Create folder called files

step 3

Create the api and upload_file Route

from fastapi import FastAPI, UploadFile, File
import shutil

app = FastAPI()

@app.post('/upload_file')
def upload_and_create_file(file : UploadFile = File(...)):
    with open(f'files/{file.filename}', 'wb') as buffer:
        shutil.copyfileobj(file.file, buffer)

    return {'msg': 'done', 'file': file.filename}
Enter fullscreen mode Exit fullscreen mode

Run the api

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

Now we are ready to Upload any file I will use requests to upload file

import requests

files = {'file': open('test.mp4', 'rb')}
res = requests.post('http://127.0.0.1:8000/upload_file', files=files)
print(res.json())
Enter fullscreen mode Exit fullscreen mode

result

{'msg': 'done', 'file': 'test.mp4'}
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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .