Flask framework - Restful, PostMan tools

1.Restful

Restful API is a set of specifications used to communicate between the front end and the background. It can provide web services for all clients through a unified interface, realize the separation of front and back ends, and save development time. The restful API is provided by the background, that is, SERVER, and called by the front end. The front end calls the API to initiate an HTTP request to the background, and the background responds to the request and feeds back the processing results to the front end. In other words, restful is a typical HTTP based protocol.

Restful API has the following design principles and specifications:

(1) Resources: the first is to clarify the concept of resources. A resource is an entity, a text, a picture or a song on the network. Resources always reflect their content through a carrier. Text can be in TXT, HTML or XML, and pictures can be in JPG or PNG format. JSON is the most commonly used resource representation.

(2) Unified interface: the Restful data element operations CRUD (create,read,update,delete) correspond to HTTP methods respectively: GET is used to obtain resources, POST is used to create new resources (or update resources), PUT is used to update resources, and DELETE is used to DELETE resources, so as to unify the interface of data operations.

(3) Uri: a URI (uniform resource locator) can be used to point to a resource, that is, each URI corresponds to a specific resource. To get the URI of this resource, you can access it, so the URI becomes the address or ID of each resource. Generally, each resource has at least one URI corresponding to it, and the most typical URI is URL.

(4) In the url link, there can be no verbs, only nouns. And for some nouns, if they appear in the plural, they should be followed by s. For example, to get a list of articles, you should use articles instead of get_article.

Flash restful plug-in

If you use flash restful, you must inherit from flash restful when defining the view function Resource class, and then define the corresponding method according to the method of the current request.

Install before use: PIP install flash restful and bind;

from flask import Flask
from flask_restful import Api

app = Flask(__name__)

# RestfulApi binding app
api = Api(app)

if __name__ == '__main__':
    print(app.url_map)
    app.run()

At goods / views Py file. When using ORM model or user-defined model, it will automatically obtain the corresponding fields in the model, generate json data, and then return it to the client. You also need to import flash here_ restful. marshal_ With decorator, and you need to write a dictionary to indicate the field to be returned and the data type of the field.

from flask_restful import Resource, reqparse, marshal_with, fields

class GoodsView(Resource):
    def get(self):
        return {'id':1,'name':'Jocelyn'}

    return_fields = {
        'id': fields.Integer,
        'username':fields.FormattedString('pre-{username}'),
        'age':fields.Integer(default=20),
        'favirate':fields.List(fields.String),
        #  Complex structure
        'school':fields.Nested({
            'address':fields.String
        })
    }

    @marshal_with(return_fields)
    def post(self):
        # username password email
        # Create reqparse object
        parser = reqparse.RequestParser()
        # Write validation rule add_argument
        parser.add_argument('username',required=True)
        parser.add_argument('password',required=True)
        parser.add_argument('email',required=True,type=str)

        # Information queried from the database
        user = {
            'id':1,
            'username':'Jocelyn',
            'password':'112233',
            # 'age':20
            'favirate':['Basketball','Football','Table Tennis'],
            'school': {'name': 'Xinhua primary school', 'address': 'Shenzhen Longhua'}
        }

        # Turn on validation
        try:
            args = parser.parse_args()
            return user

        except:
            return {'msg':'Data out of specification'}

To verify the above, we can use the PostMan tool.

2.PostMan tool

If you want to debug the request information, response information, etc. in the whole process of sending the request from the web address, you can use the PostMan tool.

Taking the above as an example, when making a POST request, fill in the requirements in Headers; If it is a GET request, it is in Params;

Keywords: RESTful Flask PostMan

Added by claire on Sun, 09 Jan 2022 10:47:17 +0200