Wednesday, 2 February 2022

FastAPI: Upload a file

We can upload the file using File function.

Prerequisite

Install ‘python-multipart’ module.

 

pip install python-multipart

pip3 install python-multipart

 

Step 1: Import File, UploadFile from fastapi module.

from fastapi import FastAPI, File, UploadFile

 

Step 2: Define File parameters.

 

Reading as bytes

@app.post("/files/")
async def create_file(file: bytes = File(...)):
    return {"file_size": len(file), "data_received" : str(file)}

 File content is read as bytes and content is uploaded as form data. In this example, file content will be read into in-memory. Use this option while reading small size files.

 

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    content = file.file.read()
    return {"filename": file.filename, "data_received": content}

 

'UploadFile' store the file content in memory upto certain size and after passing this limit it stores the file to disk.

 

uploadFile1.py

 

from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/files/")
async def create_file(file: bytes = File(...)):
    return {"file_size": len(file), "data_received" : str(file)}

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    content = file.file.read()
    return {"filename": file.filename, "data_received": content}

Open terminal and execute the command ‘uvicorn uploadFile1:app --reload’.

$ uvicorn uploadFile1:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [44194] using statreload
INFO:     Started server process [44196]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Open the url ‘http://localhost:8000/docs’ in browser and experiment with the apis.


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment