Introduction

We will create here Python Flask REST API file upload example though we have see 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 we are going to use light-weight framework called Flask to build REST API for uploading a single file.

Prerequisites

Python 3.7.4, Flask 1.1.1

Creating Project Directory

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

We 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

We will configure application through flask framework. We will also define our file upload location and maximum size of the file a user can upload.

We 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 we will create REST endpoint that will be used to upload a single file into the server.

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

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

Only with successful operation we send response status 201 otherwise we 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, 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

We 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

Thanks for reading.

Tags:

Leave a Reply

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