Web API interface specifications and test methods

Web API interface specifications and test methods

1. Web API interface

Interface: It specifies the request method for submitting request parameters and the URL link that can be accessed to obtain the corresponding feedback data. 4.parts: URL link + request method + request parameter + response data.

1.1 4.characteristics of the interface

  • url: looks like a url link that returns data
    • https://api.map.baidu.com/place/v2/search
  • Request method: get, post, put, patch, delete
    • Use the get method to request the upper interface
  • Request parameters: key-value type data in json or xml format
    • ak: 6E823f587c95f0148c19993539b99295
    • region: Shanghai
    • query: KFC
    • output: json
  • Response result: data in json or xml format
    • The output parameter value of the above request parameter determines the format of the response data
{
    "status":0,
    "message":"ok",
    "results":[
        {
            "name":"KFC (Ro restaurant)",
            "location":{
                "lat":31.415354,
                "lng":121.357339
            },
            "address":"2380 Yueluo Road",
            "province":"Shanghai",
            "city":"Shanghai",
            "area":"Baoshan District",
            "street_id":"339ed41ae1d6dc320a5cb37c",
            "telephone":"(021)56761006",
            "detail":1,
            "uid":"339ed41ae1d6dc320a5cb37c"
        }
        ...
        ]
}

1.2 Preparation of interface documentation: YApi

YApi is an open source visual interface management platform of Qunar.com's front-end technology center .

The YApi project can be built on any local or cloud server to complete the interface writing during background project development. Provide visual interface preview for development, testing and other personnel.

Qunar also provides a YApi test site on the Internet : http://yapi.demo.qunar.com/ , we can learn how YApi is written through the test site

  • Visit the test site
  • Create interface project
  • Create interface
  • Write interface

1.3 Interface test tool: Postman

Postman is an interface debugging tool, a free visualization software, supports various operating system platforms, and is the preferred tool for testing interfaces.

Postman can be downloaded directly from the official website: https://www.getpostman.com/downloads/ , and then install it in a fool-proof manner.

  • Work panel
  • Simple get request
  • Simple post request
  • Case: request Baidu map interface

2. Interface specification (restful)

RESTful (Representational State Transfer) is currently the more popular Web API design specification. Its characteristics are simple and easy to use.

2.1URL design

2.1.1 Data security (https)

  • URL links generally use the https protocol for transmission. Note: Using the https protocol can improve the security of the data interaction process

2.1.2 Interface feature performance

The interface is used to manipulate data, which is different from the URL (operation page), so specific keywords are used to express the interface.

  • Use api keyword to identify the interface url:

    Note: Seeing that the api represents the request url link is to complete the front and back data interaction.

2.1.3 Coexistence of multiple data versions

  • If a resource has multiple versions of results, use specific symbols in the URL link to be compatible with multiple versions, such as v1, v2
    • https://api.baidu.com/v1
    • https://api.baidu.com/v2

    Note: v1 and v2 in the url link are the embodiment of different data versions

2.1.4 Data is a resource

  • Interfaces are generally used to complete the interaction of front and back data, the interactive data we call resources
    • https://api.baidu.com/users
    • https://api.baidu.com/books
    • https://api.baidu.com/book

    Note: It is generally recommended to use the plural form of resources. Try not to use verbs to manipulate resources in URL links. Error demonstration: https://api.baidu.com/delete-user

  • Verbs can appear in special interfaces, because these interfaces generally do not have a clear resource, or verbs are the core meaning of the interface
    • https://api.baidu.com/place/search
    • https://api.baidu.com/login
  • Group resource operations generally have additional restrictions, such as sorting, restricted debugging, paging, etc., such as:
    • https://api.baidu.com/v1/books/?ordering=-price&limit=3

2.1.5 Resource operation is determined by the request method

  • Operation resources generally involve addition, deletion, modification, and check. We provide a request method to identify addition, deletion, modification, and check actions.
  • get: Get single or multiple resources
    • https://api.baidu.com/books-get request: get all books
    • https://api.baidu.com/books/1-get request: get the book whose primary key is 1
  • post: add single or multiple resources
    • https://api.baidu.com/books-post request: add a new book order, submit a single data dictionary, complete the order increase, return a single result object group increase, provide an array of multiple data dictionaries, complete the group increase To return multiple result objects
  • put: modify single or multiple resources as a whole
    • https://api.baidu.com/books/1-put request: modify the book whose primary key is 1 as a whole, complete the single modification, and return a single result object
    • https://api.baidu.com/books/Modify multiple data as a whole, provide multiple data dictionary numbers (the data dictionary must contain the primary key), complete the group change, and return multiple result objects
  • patch: Locally modify single or multiple resources. The modification method is exactly the same as put. The difference is that if the operated resource has multiple kv key-value pairs, the dictionary returned by the put request contains all the data, while the data returned by the patch request can be Any (optional, one or more specified) key-value pairs in the dictionary.
  • delete: delete single or multiple resources,

Single delete, no need to provide additional data, complete single delete without any resource return (usually we will return result information: success|failure)

  • https://api.baidu.com/books/1 Delete the book whose primary key is 1

Multiple deletions, provide multiple resource primary key data, complete group deletion without any resource return (usually we will return result information: success|failure)

  • https://api.baidu.com/books/(pk)/

2.2 Response status code

Network status code and network status information appear together, no additional settings

2.2.1 Normal response

  • Response status code 2xx
    • 200: Regular request
    • 201: Created successfully

2.2.2 Redirect response

  • Response status code 3xx
    • 301: Permanent redirect
    • 302: Temporary redirect

2.2.3 Client exception

  • Response status code 4xx
    • 403: Request without permission
    • 404: The requested path does not exist
    • 405: Request method does not exist

2.2.4 Server exception

  • Response status code 5xx
    • 500: Server exception

2.3 Response results

2.3.1 The response data must have status code, status information and the data itself

Data status code:

'''
0: success
1: Failure 1xx: specific failure information (to be clearly written in the interface document)
2: No data 2xx: specific no data information (to be clearly written in the interface document)
'''

Data status information

The data status information is generally not only an explanation of the data status code, but also a description of the result for the front-end developers to read.

{
    "status": 0,
    "msg": "ok",
    "results":[
        {
            "name":"KFC (Ro restaurant)",
            "location":{
                "lat":31.415354,
                "lng":121.357339
            },
            "address":"2380 Yueluo Road",
            "province":"Shanghai",
            "city":"Shanghai",
            "area":"Baoshan District",
            "street_id":"339ed41ae1d6dc320a5cb37c",
            "telephone":"(021)56761006",
            "detail":1,
            "uid":"339ed41ae1d6dc320a5cb37c"
        }
        ...
        ]
}

Data result (constant, array, dictionary), if there are sub-resources (picture, audio, video), return the URL link of the resource.

{
    "status": 0,
    "msg": "ok",
    "results":[
        {
            "name":"KFC (Ro restaurant)",
            "img": "https://image.baidu.com/kfc/001.png"
        }
        ...
        ]
}

3. CBV (as_view()) source code analysis

The Django project is started, and the start entry is manage.py. The settings file is loaded first. The settings file loads the attributes and methods of the configuration file through string reflection. If we comment out an app in the configuration file, there will be no other app. Import the file of the app, then the app will not be loaded by the project (nor will it be compiled) when it starts.

The routing layer of CBV:

from. import views
from django.conf.urls import url

urlpatterns = [

    url(r'^books/$',views.BookView.as_view()),
    url(r'^books/(?P<pk>\d+)/$',views.BookView.as_view()),

]

Here as_view is the method of the base class of BookView. What does as_view do when the project starts? Look at the source code of as_view:

    @classonlymethod
    def as_view(cls, **initkwargs):#Class method, so it can be called by class name. method name()
        """
        Main entry point for a request-response process.
        """
       # The initkwargs is empty when the project is started, do not go through the following loop
        for key in initkwargs:
            if key in cls.http_method_names:
                raise TypeError("You tried to pass in the %s method name as a "
                                "keyword argument to %s(). Don't do that."
                                % (key, cls.__name__))
            if not hasattr(cls, key):
                raise TypeError("%s() received an invalid keyword %r. as_view "
                                "only accepts arguments that are already "
                                "attributes of the class."% (cls.__name__, key))
        
        # Request comes to complete the response function
        #wsgi protocol splits the data sent by the browser into the request
        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            #Class instantiated objects
            
            #Using reflection to add a get request, get is the same as head
            if hasattr(self,'get') and not hasattr(self,'head'):
                self.head = self.get
            # Add attributes to objects
            self.request = request
            self.args = args #unnamed grouping parameters
            self.kwargs = kwargs # parameters of a famous group 
            
            #Return the execution result to the foreground
            return self.dispatch(request, *args, **kwargs)
        #The role of the following two sentences: save the request to call the view information in the view object
        view.view_class = cls
        #Add the class name to the namespace of the view
        view.view_initkwargs = initkwargs
        #Add the parameters carried by as_view to the namespace
        
        # take name and docstring from class
        update_wrapper(view, cls, updated=())

        # and possible attributes set by decorators
        # like csrf_exempt from dispatch
        update_wrapper(view, cls.dispatch, assigned=())
        
        #Return the address of the function called by the request for routing binding
        return view

    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)

dispatch method

    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        #Judging whether the requested method exists by reflection, add () call if it exists, and report an error if it does not exist
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)

4. Use pycharm to view the members of a py file

5. Use of Pycharm debug window

5.1 Operation steps:

5.1.1 Add a breakpoint: directly click the left button of the mouse at the mark. (To delete a breakpoint, just click on the breakpoint again)

5.1.2 Run the code under Debug: first break the part of the code that needs to find bugs, and then click the ladybug in the work bar to enter the debug mode.

5.1.3 Perform code debugging in accordance with the required debugging. The debugging method of Debug is as follows:

They are:

1.show execution point (Alt+F10) shows all current breakpoints

2.step over (F8) Single step debugging.

If there is sub-function a in function A, it will not enter sub-function a to perform single-step debugging, but take sub-function a as a whole and execute it in one step.

3.step into (F7) single step debugging.

If there is sub-function a in function A, it will enter sub-function a to perform single-step debugging.

4.step into my code(Alt + Shift +F7) execute the next line but ignore libraries (statements that import libraries)

5.force step into(Alt + Shift +F7) execute the next line to ignore lib and construct objects, etc. (currently it feels useless)

6.step out (Shift+F8) When the current execution is in sub-function a, select this debugging operation to directly jump out of sub-function a without continuing to execute the remaining code in sub-function a. And return to the previous function.

7.run to cursor(Alt +F9) jump directly to the next breakpoint

9. Temporarily disable breakpoints, you can disable all breakpoints

10. Quickly view and cancel breakpoints

11. View the namespace of all variables in the debug window

Reference: https://cloud.tencent.com/developer/article/1560236 Web API interface specifications and test methods-Cloud + Community-Tencent Cloud