Python Flask REST API File Upload Example

File Upload

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/2.0.1 (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

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 File Upload 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 File Upload 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

3 thoughts on “Python Flask REST API File Upload Example

Leave a Reply

Your email address will not be published. Required fields are marked *