Flask

Building a Thin API Proxy

                
            

What We'll Cover

  1. Introduction to Flask
    • What is Flask?
    • Typical Application Structure
    • What it can and can't do
  2. Why Build a Proxy?
  3. Demo

We will not cover:

  • Python
  • REST concepts and background
  • API design principles
  • Security considerations
  • Kittens
from flask import Flask, render_template, jsonify, request

app = Flask(__name__)

@app.route('/index')
def index():
    return render_template("index.html")

@app.route('/purchase/<int:product_id>', methods=['POST'])
def purchase(product_id):
    quantity = request.form['quantity']
    # ... make restful API calls with form data
    return jsonify({'txn_id': '42'})

@app.route('/quote', methods=['GET'])
def quote():
    if request.method == 'GET':
        plan = request.args.get('pricing-plan')
        # ... make restful API calls with data
    return jsonify({'quote': '£25'})

if __name__ == 'main':
    app.run()
            

What is Flask?

Flask is a micro web framework, that can also be used to build a rich API.

Flask simplifies two things:

  • routing
  • and dispatching

"... bridges Werkzeug [a WSGI application] to Jinja2 to handle templating."

Read more: flask.pocoo.org/docs/design

                
    $ tree ~/projects/flask-api-proxy
    |- flask_proxy.py
    |- flask_proxy_tests.py
    |- requirements.txt
    |- static
       |- img
          |- kitten.jpg
       |- css
          |- style.css
       |- js
          |- jquery-1.7.2.js
    |- templates
       |- index.html
                
            

Simple Example

  • flask_proxy.py - main application with dispatch rules
  • flask_proxy_tests.py - unit tests
  • requirements.txt - list of library dependencies
  • static - assets
  • templates - dynamic HTML

This is the basis for any Flask application.

You can further extend this by using libraries (eg. SQLAlchemy, Flask-OAuth) if you need to, but the idea is to use Flask as the foundation for web apps, and build up your application by adding extensions.

                
    $ tree ~/projects/talent-curator
    |- runserver.py 
    |- requirements.txt
    |- talent_curator    
        |- __init__.py
        |- apps
            |- core
                |- __init__.py
                |- views.py
                |- models.py
            |- profile
        |- settings
            |- __init__.py
            |- common.py
            |- development.py
            |- production.py
        |- database.py
        |- decorators.py
        |- static
            |- img
            |- css
            |- js
            |- scss
        |- templates
            |- profile
                |- index.html
            |- base.html
            |- index.html
                
                
@app.route('/candidates/list')
@login_required
def list():
    return render_template('list.html', candidates={})

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if g.user is None:
            return redirect(
                url_for('main_blueprint.login', next=request.url))
        return f(*args, **kwargs)
    return decorated_function                    
                
                
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Candidate(Base):
    __tablename__ = 'candidates'

    id = Column(Integer, primary_key=True)
    first_name = Column(String(100))
    last_name = Column(String(100))

    def __init__(self, first_name, last_name=None):
        self.first_name = first_name
        self.last_name = last_name
                
            

More Advanced Example

More advanced usage of Flask, using:

  • extended directory structure and separated modules
  • decorators and custom routing for API development
  • extensions for relational modeling and API connectivity (e.g. SQLAlchemy, OAuth)

What is an API Proxy?

  • Thin component, exposing internal services over HTTP endpoints.
  • Encapsulates complexity of proprietary messaging protocols (RMI, SOAP, XML, JMS).
  • Allows clients to have one uniform interface for accessing services.
  • Forward API requests to the appropriate product tier.
Tiered API Architecture

Why Build a Proxy?

I. Consolidate messaging protocols.

  • Adopt a standard messaging format and protocol (e.g. JSON over HTTP).

II. Provide a uniform interface (ie. Façade) to internal services.

  • Adapt existing services and expose uniform endpoints (e.g. REST).

Our goal is to reduce complexity through separation of components and use layered tiers to allow extensions while limiting the effect of changes.

Demo

  • Web application connecting to Google API
  • Authenticate using OAuth 2.0
  • Retrieve an object from the API and render the response
  • Demonstrate Flask routing and rendering
  • Fork on Github: github.com/tantastik/talent-curator

Further Reading References

Thank you!

This presentation was brought to you by deck.js!

1 / 48

#