RESTful API Authoring Guide

Source: Internet
Author: User
Tags oauth

Good restful APIs can be developed quickly based on some good restful development components, but without understanding the fundamentals of a well-developed, robust restful API, even good restful development components are not well understood and used. The following Gevin combined with their own hands-on experience, sorting out the key points of developing restful APIs from scratch, complete restful development components will basically contain all or most of the points, for support is not enough points, we can also write their own code implementation.

1. Request and Response

The development and use of RESTful APIs is nothing more than a client sending requests to the server (request), and the server responding to client requests (response). The true RESTful architecture style features a unified interface that uses different HTTP methods to express different behaviors:

    • GET (SELECT): Remove resources from the server (one or more items)
    • POST (Create): Create a new resource on the server
    • PUT (UPDATE): Update resources on the server (client provides full resource data)
    • PATCH (UPDATE): Updates resources on the server (client provides resource data that needs to be modified)
    • Delete: Delete A resource from the server

The client sends a request for data to the server based on a GET method, or a request to the server to send the updated data based on or method, and the PUT PATCH service side, when designing the API, also handles the corresponding request according to the specification, which should now become all restful API developer consensus, and the request and response classes of each Web framework are powerful, with reasonable default settings and flexible customization, Gevin here only to emphasize the response to these request, Common response to include the data and Status codes (status code), imperfect content, welcome to add:

    • When GET , PUT and the PATCH request succeeds, to return the corresponding data, and the status code 200 , namely success
    • When the POST data is created successfully, return the created data, and the status code 201 , i.e. created
    • When DELETE delete data is successful, no data is returned, status code is returned 204 , i.e. no CONTENT
    • When GET data is not reached, the status code is returned 404 , that is, not FOUND
    • At any time, if there is a problem with the request, such as when verifying the request data, to return the status code 400 , the bad Request
    • When the API request requires user authentication, if the authentication information in request is incorrect, return the status code 401 , i.e. not AUTHORIZED
    • When the API request needs to verify the user rights, if the current user does not have the appropriate permissions, to return the status code 403 , that is forbidden

Finally, for request and Response, don't ignore the Content-type in the HTTP header. In JSON, for example, if the API requires the client to send a request to the JSON data, then the server side only completes the JSON data acquisition and parsing, but if the service side supports the introduction of multiple types of data, such as supporting both JSON and Form-data, Then, according to the Content-type in the header when the client sends the request, the data of different types is obtained and resolved separately, if the API responds to the client request, it needs to return the JSON data, which needs to be added in the header Content-Type=application/json .

2. Serialization and deserialization

Serialization and deserialization are serialized and deserialized. RESTful API to standardize the format as a carrier of data, commonly used in the format json or xml , in the JSON format as an example, when the client sends a request to the server, or the server corresponding client request, when the client returns data, is the transmission of JSON-formatted text, And inside the server, the data processing is basically not the JSON format of the string, but the type of native, the most typical instance of the class, that is, objects (object), JSON only for the server and client communication, the data transmitted over the network format, server and client internal, There are requirements for converting JSON to native type data and converting native type data to JSON, where the native type data is converted to JSON 序列化 , and the JSON is converted to native type data 反序列化 . While some development languages, such as Python their native data types list and the dict ability to serialize and deserialize easily, are always used as vectors of data for complex APIs, so ensuring that the serialization and deserialization methods are implemented is the development of restful One of the most important steps in preparing your API

Off-topic, serialization and deserialization make the RESTful API cross-platform feature, making rest replace RPC as the mainstream of Web service

Serialization and deserialization is a hard requirement in the development of restful APIs, so almost every common development language has one or more excellent open source libraries for serialization and deserialization, so when we develop our restful APIs, there is no need to create repetitive wheels, choose a good library , such as marshmallow in Python, can be in the Django REST framework if it is based on Django development serializer .

3. Validation

validation, or data validation, is another important part of developing robust restful APIs. Still in JSON, for example, when the client sends to the server post , put or patch requests, usually at the same time to send the server JSON format related data, the server before doing data processing, the first to do the check, is the most reasonable and secure front-end interaction. If the data sent by the client is incorrect or unreasonable, the server will return 400 errors and corresponding data error messages directly to the client after the verification. Common data checks include the following:

    • Data type validation, such as the field type if it is int, then the value of assigning a string to the field is an error
    • Data format validation, such as a mailbox or password, whose assignment must satisfy the corresponding regular expression, is the correct input data
    • Data logic checks, such as data containing the date of birth and age of two fields, if the data of the two fields are inconsistent, the data validation fails

The above three types of checks, data logic verification is the most complex, usually involves a number of field mates, or to combine users and permissions to do the corresponding check. While validation is an option in the writing of RESTful APIs, it is important for the security of the API, the cost of the server, and the friendliness of the interaction, so Gevin suggests that when developing a complete set of restful APIs, The implementation of validation is essential.

4. Authentication and Permission

Authentication refers to the user authentication, permission refers to the authority mechanism, which two points is to make restful API powerful, flexible and secure basic protection.

Common authentication mechanisms are Basic Auth and OAuth , in the development of RESTful APIs, unless the API is very simple and there is no potential security issue, the authentication mechanism must be implemented and applied to the API. Basic Authvery simple, many frameworks are integrated Basic Auth implementation, their own write one can be quickly done, OAuth has become the standard enterprise-class services, its related open source implementation is very rich (more).

I have described in more detail in the RESTful Architecture style Overview, 认证机制 and interested students may wish to read the relevant chapters.

The permission mechanism is a step closer to the API request, and only the authenticated user meets the permission requirements to access the API. The specific implementation of the authority mechanism usually relies on the business logic and the application scenario of the system, generally speaking, the common permission mechanism mainly consists 全局型 of the and 对象型 , the global type of the permission mechanism, mainly refers to the user by assigning permissions, or to give the user a role or division to the user group, Then for the role or user groups to give permission to the way to implement the rights control, object-type permissions mechanism, mainly refers to the granularity of the permission control on the object, the user to a specific object access, modification, deletion or its behavior, to separate on the object for the user to give the relevant permissions to achieve permission control.

The global type of permission mechanism is easy to understand, the implementation is simple, there are many open source libraries to do the alternative, a lot of perfect web development framework, will also integrate the relevant permissions logic, object permission is relatively difficult to complicate a bit, but there are many typical applications, such as the multi-person blog system, The author's editor's right to his own article is Object permission, and its corresponding open source library has many.

Note: I wrote a "Implementation of the Django permissions mechanism," which Django developers can read.

To develop a complete set of restful APIs, the authority mechanism must be taken into account, although the specific implementation of the authority mechanism depends on the business, the authority mechanism itself, there is a typical pattern exists, need the developer to master the basic Rights mechanism implementation Scheme, in order to apply to the API at any time.

5. CORS

Cors is Cross-origin resource sharing, in the development of RESTful API, mainly for JS service, solve the cross-domain problem when JavaScript calls RESTful API.

Because of the inherent security mechanism, the cross-domain request of JS cannot be successfully responded by the server. Now the front-end separation is increasingly becoming the main trend of web development, the background gradually refers to the provision of API services for each client to provide data and related operations, and the development of the Web site all to the front end, the site and API services are rarely deployed on the same server and use the same port, JS cross-domain requests, when developing a restful API, it is often necessary to consider the implementation of the Cors feature so that JS can use the API normally.

At present, the mainstream web development language has a lot of excellent implementation of cors open Source Library, we in the development of RESTful API, we should pay attention to the implementation of cors function, directly take the existing wheel to use.

For more information about Cors, interested students can view Nanyi's cross-domain resource sharing CORS detailed

6. URL Rules

RESTful APIs are written for developers to consume, and their naming and structuring needs to be meaningful. Therefore, when designing and writing URLs, you should conform to some specifications. URL rules can be written in a separate blog to elaborate, this article only lists some key points.

6.1 Version your API

The canonical API should contain version information, and in the RESTful API, the simplest way to include the version is to put the version information in the URL, such as:

/api/v1/posts//api/v1/drafts//api/v2/posts//api/v2/drafts/

Another elegant approach is to use the HTTP header accept to deliver version information, which is also a strategy taken by the GitHub API.

6.2 Use nouns, not verbs

The URLs in the RESTful API are pointers to resources, not behaviors, so when designing an API, you should use nouns rather than verbs to describe semantics, which can cause confusion and ambiguity. That

# Bad APIs/api/getArticle/1//api/updateArticle/1//api/deleteArticle/1/

The above four URLs all point to the same resource, although a resource allows multiple URLs to point to it, but different URLs should express different semantics, the above API can be optimized to:

# Good APIs/api/Article/1/

Article resources are obtained, updated and deleted separately GET , PUT and the DELETE method requests API. Imagine PUT how uncomfortable it would feel to request a method if the URL was described by a verb /api/deleteArticle/1/ .

6.3 GETand HEADshould always be safe

RFC2616 has made it clear that GET and HEAD methods must always be safe. For example, there is an API that is not canonical:

# The following api is used to delete articles# [GET]/api/deleteArticle?id=1

Imagine if the search engine visited the above URL?

6.4 Nested Resources Routing

If you want to get a subset of resources, adoption nested routing is an elegant way, for example, to list articles in all articles that belong to Gevin:

# List Gevin‘s articles/api/authors/gevin/articles/

Another way to get a subset of resources is based on the filter following (see section below), both of which conform to the specification, but have different semantics: if semantics treat a subset of resources as a separate collection of resources, it is more appropriate to use it nested routing more appropriately if a subset of resources is obtained for filtering purposes filter .

As for the way in which the RESTful API should be written, the benevolent see, semantically speaking, can be used.

6.5 Filter

For resource collections, you can filter resources by URL parameters, such as:

# List Gevin‘s articles/api/articles?author=gevin

Paging is one of the most typical resource filters.

6.6 Pagination

For a resource collection, paging is a reasonable way to get it. If you are using the paging mechanism in the development framework directly, based on the development framework (such as the Django REST framework), if you implement the paging mechanism yourself, the Gevin strategy is:

Returns a collection of resources that contain data related to paging as follows:

{  "page": 1,            # 当前是第几页  "pages": 3, # 总共多少页 "per_page": 10, # 每页多少数据 "has_next": true, # 是否有下一页数据 "has_prev": false, # 是否有前一页数据 "total": 27 # 总共多少数据}

When you want the API to request a resource collection, the optional paging parameters are:

Parameters meaning
Page Current page, default is 1
Per_page How many records per page, default to system default values

In addition, a field is set up within the system to per_page_max mark the maximum number of records per page allowed by the system, and the per_page number of records per page when the value is greater than the per_page_max value per_page_max .

6.7 Url Design Tricks

(1) URLs are case-sensitive, which is often overlooked, namely:

    • /Posts
    • /posts

The above two URLs are different two URLs that can point to different resources

(2) Back forward Slash ( / )

Currently the popular API design, usually recommend URLs / as the end, if the API GET request, URL does not end, then redirect to the / / end of the API (which is now the basic support of the web framework), because there is no /, also two URLs, namely:

    • /posts/
    • /posts

This is also a two different URLs that can correspond to different behaviors and resources

(3) Connectors - and underscores_

RESTful APIs should be readable, and when a fragment (segment) in a URL is made up of multiple words, it is recommended to use it - to partition the word instead of using it _ , namely:

# Good/api/featured-post/# Bad/api/featured_post/

This is mainly because the default effect of hyperlinks in the browser is that the text is underlined, and if the API is to _ partition words, they overlap and affect readability.

Summarize

The original intention of this article is to tidy up a set of basic ideas for writing standard, secure restful APIs from scratch. This article describes the basic things to consider when developing a restful API, which can be started with the content of this article for a web framework like flask, which natively supports restful styles, and does not rely on other restful third-party libraries to develop restful services. Many powerful restful Library, although its related interface basically covers all or most of the content of this article, but the summary of this article, I believe that the understanding and use of these libraries is also helpful.

Finally, about how to develop the restful API, welcome everyone to communicate with me ~

RESTful API Authoring Guide

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.