Python Flask REST API File Upload Example

Introduction

I will create here Python Flask REST API file upload example though you might have seen how to upload file using Python Flask in web application. You may need to upload a single file or multiple files into your application for a reason and here I am going to use light-weight web based Python framework called Flask to build REST API for uploading a single file.

Prerequisites

Python 3.7.4 – 3.9.1, Flask 1.1.1 – 1.1.2 (pip install flask)

Project Directory

Create a project root directory called python-flask-rest-api-file-upload as per your chosen location.

I may not mention the project’s root directory name in the subsequent sections but we will assume that we are creating files with respect to the project’s root directory.

Related Posts:

Configuring Application

I will configure application through flask framework. I will also define file upload location (C:/uploads) and maximum size (16*1024*1024 bytes) of the file a user can upload.

You should not allow user to upload unlimited size of file due to security reasons or to avoid exhausting server space.

Create a file called app.py with the below code.

from flask import Flask

UPLOAD_FOLDER = 'C:/uploads'

app = Flask(__name__)
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

Configuring REST Endpoint

Now I will create REST endpoint that will be used to upload a single file into the server.

I will show a successful message once file uploaded successfully or error message depending on the server error.

I will define a method allowed_file(filename) to allow user only upload allowed file types.

Only with successful operation it will send response status 201 otherwise it will send 400 bad request with error message.

Create a file main.py with the below source code.

import os
import urllib.request
from app import app
from flask import Flask, request, redirect, jsonify
from werkzeug.utils import secure_filename

ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):
	return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/file-upload', methods=['POST'])
def upload_file():
	# check if the post request has the file part
	if 'file' not in request.files:
		resp = jsonify({'message' : 'No file part in the request'})
		resp.status_code = 400
		return resp
	file = request.files['file']
	if file.filename == '':
		resp = jsonify({'message' : 'No file selected for uploading'})
		resp.status_code = 400
		return resp
	if file and allowed_file(file.filename):
		filename = secure_filename(file.filename)
		file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
		resp = jsonify({'message' : 'File successfully uploaded'})
		resp.status_code = 201
		return resp
	else:
		resp = jsonify({'message' : 'Allowed file types are txt, pdf, png, jpg, jpeg, gif'})
		resp.status_code = 400
		return resp

if __name__ == "__main__":
    app.run()

Deploying the Application

Now navigate to the project’s root directory using command line tool and execute the command python main.py or main.py (if Python is on the classpath), your server will be started on default port 5000.

If you want to change the port then you can change the line app.run() to app.run(port=5001), where 5001 is the new port.

Testing the Application

I will test our application using Postman tool. You may also do client side programming to call the above REST endpoint and upload the file.

Related Post:

python flask rest api file upload

Verifying the C:/uploads folder:

python flask rest api file upload

That’s all. Hope you got an idea how to upload file in Python Flask REST API.

Source Code

Download

5 Thoughts to “Python Flask REST API File Upload Example”

  1. goshman

    guide was helpful.
    thanks!

  2. MXU

    You need to close your file via file.close()

  3. F0Dev

    A Question, what is the best way to send an additional value for example “file descriptive”?

  4. Kali Kimanzi

    finally worked i was leaving behind the code below aap.py code… thanks for the article

  5. Kali Kimanzi

    it is not working on my side i dont know what could be the error

Leave a Comment