The foreword 0.

In the coming weeks, Gevin will be publishing a series of articles on Flask RESTful API development. This is the first in the series called Flask RESTful Basics.

  • Basics (1) — Flask RESTful Basics
  • To Be Continued…

1. Introduction of RESTful

I have discussed in detail my understanding of RESTful architecture and what is involved in canonical RESTful API development in my blog posts Overview of RESTful Architecture style and Guide to RESTful API Writing. Here are a few highlights to lay the groundwork for the following:

  1. RESTful is resource-oriented, and each resource has at least one URL corresponding to it
  2. Unified data interaction interface, that is, over HTTPGET.POST.PUT(or PATCH), andDELETEObtain, create, update, and delete resources
  3. Resources (data) are transferred over the network in text format, usually in JSON or XML format
  4. Stateless (more on authentication later)

Flask’s support for RESTful architectural styles

Flask RESTful development has a lot of libraries, and I’ve collected some of them. In fact, unlike Django, Flask’s native support for RESTful development is pretty good. We can also develop RESTful apis that are good enough, and without the constraints of extensions, we can use the extension that best deals with the problem in the Flask ecosystem, or the extension that we are the most skilled at, during development. This is more in line with Flask’s philosophy. The main reason Gevin doesn’t use the various Flask REST extensions in Flask RESTful development is that each extension has its flaws.

So let’s take a look at how Flask native supports RESTful development.

Note: Django RESTful development is mainly based on the Django REST Framework. I have always been very interested in the DRF concept of Django. I have borrowed a lot of Django design concepts in Flask development and Flask RESTful API development. So Gevin has a good idea for how to do Flask development: Start with Django.

2.1 Flask’s support for HTTP methods

Flask natively supports all HTTP methods, such as GET, POST, PUT, PATCH, and DELETE.

@app.route('/http-method-test/', methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
def http_method_example():
    if request.method == 'GET':
        return 'Send request with `GET` method'
    elif request.method == 'POST':
        return 'Send request with `POST` method'
    elif request.method == 'PUT':
        return 'Send request with `PUT` method'
    elif request.method == 'PATCH':
        return 'Send request with `PATCH` method'
    elif request.method == 'DELETE':
        return 'Send request with `DELETE` method'

Copy the code

The alternative is to use Flask’s MethodView:

class HttpMethodExample(MethodView):
    def get(self):
        return 'Send request with `GET` method'

    def post(self):
        return 'Send request with `POST` method'

    def put(self):
        return 'Send request with `PUT` method'

    def patch(self):
        return 'Send request with `PATCH` method'

    def delete(self):
        return 'Send request with `DELETE` method'

app.add_url_rule('/http-method-test2/', view_func=HttpMethodExample.as_view('http_method_example2'))
Copy the code

2.2 Flask’s support for serialization and deserialization

In RESTful development, the data carrier is usually JSON or XML format text. With the continuous development of RESTful, JSON has become the mainstream carrier of RESTful API data. Flask, for its part, already has pretty good JSON support.

2.2.1 serialization

Serialization in RESTful API development by including the following operations:

  1. Convert Python native formatted data (such as dict and list) to textual data (such as JSON or XML)
  2. Text data is returned to the client as a response to the request, attached to the HTTP header of the responseapplication/jsonThe mimetype

These two steps are done directly by Flask’s jsonify() shortcut, as described in the official Flask documentation below:

This function wraps dumps() to add a few enhancements that make life easier. It turns the JSON output into a Response object with the application/json mimetype. For convenience, it also converts multiple arguments into an array or multiple keyword arguments into a dict. This means that both Jsonify (1,2,3) and jsonify([1,2,3]) serialize to [1,2,3].

Very simple things, should not say so much, directly on the code example bar:

class SerializationExample(MethodView): def get(self): option = request.args.get('option') if option == 'list1': return self.test_list() if option == 'list2': return self.test_list2() if option == 'dict1': return self.test_dict1() if option == 'dict2': return self.test_dict2() if option == 'dict3': return self.test_dict3() msg = { 'info': '`option` is needed in url as a url parameter', 'avilable option values': 'list1, list2, test_dict1, test_dict2, test_dict2' } return jsonify(msg) def test_list(self): data = [{'a':1, 'b':2}, {'c':3, 'd':4}] return jsonify(result=data) def test_list2(self): Data = [1,2,3,4,5,6,7,8] return jsonify(data) def dict1(self): data = {'a':1, 'b':2, 'c':3} return jsonify(data) def test_dict2(self): data = {'a':1, 'b':2, 'c':3} return jsonify(**data) def test_dict3(self): data = {'a':1, 'b':2, 'c':3} return jsonify(result=data) app.add_url_rule('/serialization/', view_func=SerializationExample.as_view('serialization'))Copy the code

The point of the code above is that the functions that start with test_ can be serialized in just one of these ways.

2.2.2 Deserialization

Deserialization, the process of converting textual data into Python Native data. Flask’s built-in get_json() method converts json data from request to dict or list in the Python standard library.

Parses the incoming JSON request data and returns it. By default this function will return None if the mimetype is not application/json, but this can be overridden by the force parameter.

If parsing fails the on_json_loading_failed() method on the request object will be invoked.

Sample code:

@app.route('/deserialization/', methods=['get', 'post'])
def deserialization():
    if request.method == 'POST':
        data = request.get_json()
        if not data:
            return 'No json data found', 400

        result = {
            'json data in request': data
        }
        return jsonify(result)

    return 'Please post json data'
Copy the code

Note:

Flask’s native serialization and deserialization methods are the most popular JSON formats for RESTful API development, and can only be used to convert JSON to dict or list. If you want to serialize or deserialize object instances, you need to use other methods, which will be further explained in future articles.

3. What’s More

  • My project restapi_Example on GitHub has the full source code for this series, which you can browse freely.

  • See the chapter1 branch of the project above for a complete example of the code covered in this chapter

  • During RESTful API development, the API test tool Postman is available

  • Next lecture: Gevin will introduce RESTful API design and implementation with a specific application example


Note: To reprint this article, please contact Gevin


Did this article help you? Welcome to join the wechat group of back-end learning Group: