Quick intro to Flask

Quick intro to Flask

What is Flask?

Flask is a web framework written in python. It is a micro web framework as it does not use any third party tools or library. It is based on Werkzeug toolkit which is a WSGI utility library and Jinja2 template engine and is BSD licensed. WSGI is a protocol which allows Python application to communicate with a web server and hence can be used as web-application outside of CGI. Flask has the ability to build the complex database driven website.
Flask provides you with tools, libraries that allows building a web application. It is a lightweight framework and there is less dependency to update third-party security bugs.

Why Flask?

  • Unlike other frameworks like Django, Flask is easier to set up.
  • It is faster and easier to run Flask based applications.
  • Flask is actively maintained and continuously developed.
  • Large documentation and developer tools available.
  • Simple to use and large number of extensions which integrate with it very well
  • Written in python and supports rapid high-level application development
  • Offers large number of useful in-house libraries

Using Flask for Restful API building

Before starting to create an API in Flask, we need to setup Virtualenv.  Virtualenv is used for most of the python based web development. This is especially useful when we need to work on multiple versions of python. Helps to ensure backward compatibility issues do not hamper your development. It provides a sophisticated way of isolating the different python environments.
To download Virtualenv you can use – https://pypi.python.org/pypi/virtualenv
To install Virtualenv you can refer – https://virtualenv.pypa.io/en/stable/installation/
Once installation of Virtualenv is completed we can start with the setup of Flask as shown below:
Flask-Restful is an extension of the existing Flask which provides support for the quick building of REST APIs. It is extremely lightweight which works with existing libraries.

Resourceful Routing:

Resources in Flask are built on top of Flask Pluggable Views. This allows you to access multiple HTTP methods just by defining methods on your resources. Sample code for this is as below:

from flask import Flask, request
from flask_restful import Resource, Api
 
app = Flask(__name__)
api = Api(app)
callApi = {}
 
class callApiResource(Resource):
    def get(self, apiId):
        return {apiId: callApi[apiId]}
 
    def put(self, apiId):
        callApi[apiId] = request.form['data']
        return {apiId: callApi[apiId]}
 
api.add_resource(callApiResource, '/<string:apiId>')
This can be tested as:

$ curl http://localhost:5000/todo1 -d "data=update the API" -X PUT
{"todo1": " update the API"}
Flask Restful can have multiple kinds of return values. In multiple return values, we can also set response code and response headers.

class Api1(Resource):
    def get(self):
        # Default to 200 OK
        return {'task': 'Hello world'}
 
class Api2(Resource):
    def get(self):
        # Set the response code to 201
        return {'task': 'Hello world'}, 201
 
class Api3(Resource): 
    def get(self):
        # Set the response code to 201 and return custom headers
        return {'task': 'Hello world'}, 201, {'Etag': 'some-opaque-string'}

Argument Parsing:

Though Flask provides access to request data by using a query string or post method, validating form data is not simple. In Flask-Restful, we have built-in support for data validation using a library similar to argparse. Unlike argparse, reqparse.RequestParser.parse_args() returns a python dictionary instead of the custom data structure.

from flask_restful import reqparse
 
parser = reqparse.RequestParser()
parser.add_argument('rate', type=int, help='Per rate charge')
args = parser.parse_args()

Data Formatting:

All fields in the return iterable are rendered as it is. Though this works well with python data structure, this is tedious in case of dealing with objects. As a solution to this, Flask-Restful provides fields module and marshal_with() decorator. The sample is as shown below.

from collections import OrderedDict
from flask_restful import fields, marshal_with
 
resource_fields = {
    'api':   fields.String,
    'uri':    fields.Url('api_test')
}
 
class APICall(object):
    def __init__(self, apiId, api):
        self.apiId = apiId
        self.api = api
        # This field will not be sent in the response
        self.status = 'active'
 
class Todo(Resource):
    @marshal_with(resource_fields)
    def get(self, **kwargs):
     return APICall(apiId='my_todo', api='Generate this API')
In this example the python object is serialized. Marshal_with() decorator will apply transformation described by resource_fields. The fields.Url takes endpoint name and generates a URL for that endpoint in the response.

Conclusion:

Flask Restful makes API creation simpler with its inbuilt functions and libraries. It provides flexibility and multiple options to make API development simpler.
———————–
Do you want to know more about web programming in python? Read here http://borsuquesquad.pl/rails-and-django-comparison/.
Post a comment