Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.
Introduction
In this blog post I will introduce you to the Flask Framework and how to build a simple To Do REST service.
“Micro” does not mean that your whole web application has to fit into a single Python file (although it
certainly can), nor does it mean that Flask is lacking in functionality. The “micro” in microframework means
Flask aims to keep the core simple but extensible. Flask won’t make many decisions for you, such as what
database to use. Those decisions that it does make, such as what templating engine to use, are easy to change.
Everything else is up to you, so that Flask can be everything you need and nothing you don’t.
A minimal Flask application looks something like this:
Directory Structure
Create files and directories as outlined below before you continue. If you are uncertain view the source
in the github repository.
In the next section we will discuss how to setup a REST service in Flask using a Flask extension library:
Flask RESTful
Setting Up
Before we set up the project we need to create a virtual environment for Python.
virtualenv is a tool to create isolated Python environments.
Install virtualenv with pip:
We can then create an isolated Python environment with:
Where venv is a directory to place the new virtual environment.
In a newly created virtualenv there will also be a activate shell script. For Windows systems, activation
scripts are provided for the Command Prompt and Powershell.
On Posix systems, this resides in /ENV/bin/, so you can run:
To undo these changes, just run:
On Windows, the equivalent activate script is in the Scripts folder:
And type deactivate to undo the changes. Now activate the virtual environement using the methods
outlined above based on your operating system.
We will organise the dependencies for the REST application in a requirements.txt file:
If it is not obvious at this point, flask-restful is flask extension for RESTful webservices and SimpleXML
is a library for very simply manipulating XML files. It lets you harvest data from XML files, change values of attributes, print or change data of elements, create new elements, etc.
Install the packages with the following command:
This pulls in Flask RESTful and SimpleXML and all their dependent packages.
Creating Utility Module for REST
We will create a small utility module to assist with GET, UPDATE, POST and DELETE operations:
In the above snippet we added abort_if_todo_doesnt_exist function to handle 404 errors when a resource with
the given id does not exist in the TODOS array.
Create the Resource Classes
Next we create the resource classes that consume the utility module:
fromsimplexmlimportdumpsfromflaskimportmake_response,Flaskfromflask_restfulimportApifromtodoapi.resourcesimporttodo_resourcedefoutput_xml(data,code,headers=None):"""Makes a Flask response with a XML encoded body"""resp=make_response(dumps({'response':data}),code)resp.headers.extend(headersor{})returnrespapp=Flask(__name__)api=Api(app,default_mediatype='application/json')api.representations['application/xml']=output_xmlapi.add_resource(todo_resource.TodoList,'/api/v1.0/resources')api.add_resource(todo_resource.Todo,'/api/v1.0/resources/<int:todo_id>')
output_xml is a marshaller for XML. On line 14 we are telling flask to use this marshaller for XML
representation. On lines 16 and 17 we map the endpoints to the representations.
Running and Testing the Endpoints
To run the service you need to set two environment variables:
Then activate the virtualenv if you haven’t already done so. Navigate to the todoapi directory i.e.
cd todoapi and run the following command:
Using cURL or a REST client of your choice test the GET endpoint:
You can also view the representation as XML:
We can get a single item using curl -i -X GET http://127.0.0.1:5000/api/v1.0/resources/1.
To delete use curl -i -X DELETE http://127.0.0.1:5000/api/v1.0/resources/1.
The POST and PUT endpoints require a body:
Conclusion
In this post we learned how to create a REST service with Flask in Python. In addition if you have built
a flask app and are ready to take your application to the next level, you can take a look at this blog
post on Flask Production Recipes.
As usual you can find the full example to this guide in the github repository. Until the next post, keep doing cool things .