Python Flask — RESTful API
Lightweight microframework
Why :
- Built-in development server and debugger
- Integrated Unit Testing support
- Easy and flexible configurations
Installation
Run command
Python3 -m pip install Flask
Implementation
from flask import Flaskapp = Flask(__name__)@app.route(‘/’) def hello_world(): return ‘Hello world’
Run / Start Server
flask run
API Endpoints
Let’s write our API endpoints in the app.py file.
Importing Libraries
from flask import Flask, jsonify, requestimport logging
POST : Handling Request Body
@app.route(‘/api/v1/doa, methods=[‘POST’]) def get_request_body(): request_data = request.get_json() title = request_data[‘title’] return title
Send request with curl command :
curl — location — request POST ‘http://127.0.0.1:5000/api/v1/doa' \ — header ‘Content-Type: application/json’ \ — data-raw ‘{“title”: “wuduk”}’
GET : Handling Query Parameters
@app.route(‘/api/v1/doa/search’) def query_example(): keyword = request.args.get(‘keyword’) logging.debug(‘keyword: %s’ % keyword) return keyword
Endpoint : http://127.0.0.1:5000/api/v1/doa/search?aktiviti=selamat
Handling Request Headers
@app.route(‘/api/v1/authorisation’, methods=[‘GET’])def api_auth(): if ‘Authorisation’ in request.headers: authkey = request.headers[‘Authorisation’] return authkey
Send request with curl command :
curl — location — request GET ‘http://127.0.0.1:5000/api/v1/authorisation' \ — header ‘Authorisation: 32vffwfwr23423’ \ — header ‘Content-Type: application/json’
GET : Handling URL Variables
@app.route(‘/api/v1/doa/<id>’, methods=[‘GET’])def api_url_variable(id):return id
Endpoint : http://127.0.0.1:5000/api/v1/doa/23
Default app.py
Run the following command if we want to change the main file, otherwise we can use the default app.py
export FLASK_APP=application.py
Database Connection : MySQL
pip3 install Flask flask-mysql
Write the following code in your main file .py :
from flaskext.mysql import MySQLmysql = MySQL()# MySQL configurationsapp.config[‘MYSQL_DATABASE_USER’] = ‘your_user’app.config[‘MYSQL_DATABASE_PASSWORD’] = ‘your_password’app.config[‘MYSQL_DATABASE_DB’] = ‘your_database_name’app.config[‘MYSQL_DATABASE_HOST’] = ‘your_host’mysql.init_app(app)@app.route(‘/api/v1/database’)def api_database(): cur = mysql.connect().cursor() cur.execute(‘’’select * from muslimbrader.doa’’’) r = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in cur.fetchall()] return jsonify({‘data’ : r})
Endpoint : http://127.0.0.1:5000/api/v1/database
Response :
Werkzeug
Flask depends on the Jinja template engine and the Werkzeug WSGI toolkit. Werkzeug is primarily a utility library for WSGI (rather than web server) although it provides a simple web server for development purposes. WSGI itself is a protocol or convention that ensures that our web application can speak with the webserver and more importantly that web applications work nicely together.
Werkzeug summary as follow :
- A comprehensive WSGI web application library
- Does not have any direct dependencies
Example of response header (I used curl command with -i argument for this) :
HTTP/1.0 200 OKContent-Type: text/html; charset=utf-8Content-Length: 5Server: Werkzeug/2.0.1 Python/3.8.5Date: Sat, 24 Jul 2021 00:32:45 GMT