Creating RESTful APIs using Flask and Python

Medium Article Link: https://medium.com/p/655bad51b24

Minimal Flask App

from flask import Flask

app = Flask(__name__)

@app.route('/hello/', methods=['GET', 'POST'])
def welcome():
    return "Hello World!"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=105)

Variable Rules

from flask import Flask

app = Flask(__name__)

@app.route('/<int:number>/')
def incrementer(number):
    return "Incremented number is " + str(number+1)

@app.route('/<string:name>/')
def hello(name):
    return "Hello " + name

app.run()

Return JSON Serializable Output

from flask import jsonify

@app.route('/person/')
def hello():
    return jsonify({'name':'Jimit',
                    'address':'India'})
from flask import jsonify

@app.route('/numbers/')
def print_list():
    return jsonify(list(range(5)))

Redirection Behaviour

@app.route('/home/')
def home():
    return "Home page"

@app.route('/contact')
def contact():
    return "Contact page"

Return Status Code

@app.route('/teapot/')
def teapot():
    return "Would you like some tea?", 418

Before Request

@app.before_request
def before():
    print("This is executed BEFORE each request.")
    
@app.route('/hello/')
def hello():
    return "Hello World!"

Blueprints

home.py

from flask import Blueprint

home_bp = Blueprint('home', __name__)

@home_bp.route('/hello/')
def hello():
    return "Hello from Home Page"

contact.py

from flask import Blueprint

contact_bp = Blueprint('contact', __name__)

@contact_bp.route('/hello/')
def hello():
    return "Hello from Contact Page"

app.py

from flask import Flask

from home import home_bp
from contact import contact_bp

app = Flask(__name__)

app.register_blueprint(home_bp, url_prefix='/home')
app.register_blueprint(contact_bp, url_prefix='/contact')

app.run()

Logging

app.logger.debug('This is a DEBUG message')
app.logger.info('This is an INFO message')
app.logger.warning('This is a WARNING message')
app.logger.error('This is an ERROR message')