Overview

This guide shows how to use the Flask Project as a Python API application. But it can also be used as Web App which is covered in a different tutorial. It shows how to perform GET and POST operations. The code contains a preview setup, it can be further enhanced to call a database or external service.

 

Prerequisites

  • Python, Virtual Environment, Pip and Flask has been installed.
  • Refer to this guide on how to install the requirements.

 

Application Structure

geek_flask_api

├── api

│   ├── __init__.py

│   └── res

│       ├── __init__.py

│       └── sample_res.py

├── venv

├── requirements.txt

└── runserver.py

 

Steps

Note that you can also perform this steps using an IDE of your choice. An example would be PyCharm.

01. Create the application directory and create the flask project.

mkdir geek_flask_api

 

02. Create the geek_flask_api/runserver.py” which will be the root or main entry point of the API application.

geek_flask_api/runserver.py

# -*- coding: utf-8 -*-
# Start Flask with default web server

from api import application
application.run(host='127.0.0.1', port=8080, debug=True)

 

03. Create the Python file, “geek_flask_api/api/__init__.py” and set the content as follows. This will create the root Flask application.

geek_flask_api/api/__init__.py

# -*- coding: utf-8 -*-
from flask import Flask
application = Flask(__name__)

import api.res.sample_res

 

Note that the sample_res is not yet created.

 

04. Create the “res” directory which will contain the REST endpoints. Create the following python script, “geek_flask_api/api/res/__init__py” and “geek_flask_api/api/res/sample_res.py
geek_flask_api/res/api/__init__.py

# Empty

 

geek_flask_api/res/api/sample_res.py

# -*- coding: utf-8 -*-

import datetime
from api            import application
from flask          import jsonify, request


@application.route('/system-info', methods=['GET'])
def get_system_info():
  info = \
    {
      'name'        : 'geek-flask-api'
      , 'version'   : '1.0.0.'
      , 'date_time' : datetime.datetime.now()
    }

  return jsonify(info)


@application.route('/users/add', methods=['POST'])
def add_user():
  username = request.form.get('username')
  password = request.form.get('password')

  print("Form parameters, username={username} and password={password}".format(username=username, password=password))

  # TODO Call service layer function to add the user

  response = \
    {
      'success': True
      , 'input' :
      {
        'username'    : username
        , 'password'  : password
      }
    }

  return jsonify(response)


@application.route('/users/<user_id>', methods=['POST'])
def update_user_info(user_id):
  json_content = request.get_json()

  print("Path param : user_id={user_id}".format(user_id=user_id))
  print("JSON content as dictionary : {json_content}".format(json_content=json_content))

  # TODO Call service layer function to update the user

  response = \
    {
      'success' : True
      , 'input' :
        {
          'user_id'         : user_id
          , 'json_content'  : json_content
        }
    }

  return jsonify(response)

 

05. In the “sample_res.py” there are 3 path that can be accessed.

[GET] /system-info

— Description   : Retrieve a JSON content with some static info and date-timestamp

— Request       : –NONE–

— Response      : JSON

[POST] /users/add

— Description    : A sample endpoint to submit form parameters to add a User

— Request (Form) :

—- FORM parameter : username

—- FORM parameter : password

— Response    : JSON

[POST] /users/<user_id>

— Description    : A sample endpoint to update the User info using a JSON content

— Request (JSON) :

{

first_name  : “”

, last_name : “”

}

— Response       : JSON

 

How To Run and Test

01. Activate the Virtual Environment. Optional if not using a Virtual Environment

$ cd geek_flask_api
$ source venv/bin/activate 

 

02. Run the Flask api

$ python runserver.py

 

03. Test by calling the “system-info” endpoint.

via cURL

$ curl http://127.0.0.1:8080/system-info

 

via Browser

 

04. The other endpoints can be tested by using cURL or any REST client like Postman.

 

Previous How To Install Matplotlib
Next Android Dev Summit 2019 | Keynote