Set up Flask app to implement GET and POST API


Flask app is one of the easiest ways to setup APIs on the server side for data engineering and data science purpose.
Here we show an simple set up process, an example python file, and how to run it in an development environment.

packages to install

assume we are using python3 environment

  1. install flask

sudo apt install python3-flask

  1. to allow Cross-Origin Resource Sharing

pip3 install flask_cors

A simple example python file (main.py) to setup flask GET and POST APIS

from flask import Flask,request
from flask_cors import CORS
import json

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"


# GET method
@app.route("/get", methods=['GET'])
def getexample():

# GET data
query = request.args.get("query", None)

print(query)

return query


#post method
@app.route("/post", methods=['POST'])
def postexample():
## Get POST input form data
#data = dict((key, request.form.get(key)) for key in request.form.keys())

# Get POST input json data
data = dict((key, request.json.get(key)) for key in request.json.keys())
print(data)
print('post request with {}'.format(data))

output={"status":"ok"}
return json.dumps(output)

to run the flask API: in the command line to run the following command

sudo FLASK_APP=main.py flask run –host=0.0.0.0 –port 3000


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC