Flask Cheat Sheet A cheat-sheet for creating web apps with the Flask framework using the Python language. Ready for Flask microframework. Now, finally, I could install Flask by running pip install flask. Editor’s Note: Using Python virtual environments and avoiding pip install as root are best practices. See How to install Python 3, pip, venv, virtualenv, and pipenv for more information.
2013-07-28T19:11:38Z
This is the third article in which I explore different aspects of writing RESTful APIs using the Flask microframework. Here is the first, and the second.
The example RESTful server I wrote before used only Flask as a dependency. Today I will show you how to write the same server using Flask-RESTful, a Flask extension that simplifies the creation of APIs.
As a reminder, here is the definition of the ToDo List web service that has been serving as an example in my RESTful articles:
HTTP Method | URI | Action |
---|---|---|
GET | http://[hostname]/todo/api/v1.0/tasks | Retrieve list of tasks |
GET | http://[hostname]/todo/api/v1.0/tasks/[task_id] | Retrieve a task |
POST | http://[hostname]/todo/api/v1.0/tasks | Create a new task |
PUT | http://[hostname]/todo/api/v1.0/tasks/[task_id] | Update an existing task |
DELETE | http://[hostname]/todo/api/v1.0/tasks/[task_id] | Delete a task |
The only resource exposed by this service is a 'task', which has the following data fields:
In my first RESTful server example (source code here) I have used regular Flask view functions to define all the routes.
Flask-RESTful provides a Resource
base class that can define the routing for one or more HTTP methods for a given URL. For example, to define a User
resource with GET
, PUT
and DELETE
methods you would write:
The add_resource
function registers the routes with the framework using the given endpoint. If an endpoint isn't given then Flask-RESTful generates one for you from the class name, but since sometimes the endpoint is needed for functions such as url_for
I prefer to make it explicit.
My ToDo API defines two URLs: /todo/api/v1.0/tasks
for the list of tasks, and /todo/api/v1.0/tasks/<int:id>
for an individual task. Since Flask-RESTful's Resource
class can wrap a single URL this server will need two resources:
Note that while the method views of TaskListAPI
receive no arguments the ones in TaskAPI
all receive the id
, as specified in the URL under which the resource is registered.
When I implemented this server in the previous article I did my own validation of the request data. For example, look at how long the PUT
handler is in that version:
Here I have to make sure the data given with the request is valid before using it, and that makes the function pretty long.
Flask-RESTful provides a much better way to handle this with the RequestParser
class. This class works in a similar way as argparse
for command line arguments.
First, for each resource I define the arguments and how to validate them:
In the TaskListAPI
resource the POST
method is the only one the receives arguments. The title
argument is required here, so I included an error message that Flask-RESTful will send as a response to the client when the field is missing. The description
field is optional, and when it is missing a default value of an empty string will be used. One interesting aspect of the RequestParser
class is that by default it looks for fields in request.values
, so the location
optional argument must be set to indicate that the fields are coming in request.json
.
The request parser for the TaskAPI
is constructed in a similar way, but has a few differences. In this case it is the PUT
method that will need to parse arguments, and for this method all the arguments are optional, including the done
field that was not part of the request in the other resource.
Now that the request parsers are initialized, parsing and validating a request is pretty easy. For example, note how much simpler the TaskAPI.put()
method becomes:
A side benefit of letting Flask-RESTful do the validation is that now there is no need to have a handler for the bad request code 400 error, this is all taken care of by the extension.
My original REST server generates the responses using Flask's jsonify
helper function. Flask-RESTful automatically handles the conversion to JSON, so instead of this:
I can do this:
Flask-RESTful also supports passing a custom status code back when necessary:
But there is more. The make_public_task
wrapper from the original server converted a task from its internal representation to the external representation that clients expected. The conversion included removing the id
field and adding a uri
field in its place. Flask-RESTful provides a helper function to do this in a much more elegant way that not only generates the uri
but also does type conversion on the remaining fields:
The task_fields
structure serves as a template for the marshal
function. The fields.Url
type is a special type that generates a URL. The argument it takes is the endpoint (recall that I have used explicit endpoints when I registered the resources specifically so that I can refer to them when needed).
The routes in the REST server are all protected with HTTP basic authentication. In the original server the protection was added using the decorator provided by the Flask-HTTPAuth extension.
Since the Resouce
class inherits from Flask's MethodView
, it is possible to attach decorators to the methods by defining a decorators
class variable:
The complete server implementation based on Flask-RESTful is available in my REST-tutorial project on github. The file with the Flask-RESTful server is rest-server-v2.py.
You can also download the entire project including both server implementations and a javascript client to test it:
Download REST-tutorial project.
Let me know if you have any questions in the comments below.
Miguel
Hello, and thank you for visiting my blog! If you enjoyed this article, please consider supporting my work on this blog on Patreon!
#1Kuan said 2013-07-29T01:38:04Z
#2rick said 2013-07-29T04:03:41Z
#3Marco Massenzio said 2013-08-02T07:33:49Z
#4Daniel Donovan said 2013-08-03T18:56:00Z
#5Danny said 2013-08-06T20:50:39Z
Wps office 2016 serial key. #6Dan said 2013-08-11T06:58:56Z
#7Akshay said 2013-08-26T06:54:29Z
#8Tim said 2013-09-05T12:07:35Z
#9Miguel Grinberg said 2013-09-06T16:11:32Z
#10Chitrank Dixit said 2013-10-05T07:05:05Z
#11Dave Barndt said 2013-10-16T03:36:06Z
Visual studio free download torrent. #12Miguel Grinberg said 2013-10-16T16:27:14Z
#13Miguel Grinberg said 2013-10-16T16:34:33Z
#14ryzhiy said 2013-10-16T21:44:01Z
#15Miguel Grinberg said 2013-10-17T04:25:42Z
#16ryzhiy said 2013-10-18T07:50:11Z
#17Hooman said 2013-10-22T12:08:16Z
#18Miguel Grinberg said 2013-10-22T14:13:32Z
#19Dave Barndt said 2013-10-22T19:48:11Z
#20Miguel Grinberg said 2013-10-22T21:13:54Z
#21Dave Barndt said 2013-10-23T17:15:15Z
#22Dave Barndt said 2013-10-25T15:09:45Z
#23Miguel Grinberg said 2013-10-25T16:09:55Z
#24Dave Barndt said 2013-10-25T16:17:13Z
#25Miguel Grinberg said 2013-10-25T16:32:26Z