REST vs RESTFul API Best Practices

    I often interview developers who do PHP, and it makes me wonder that there are always more than 8 out of 10 people who don't know what a REST service is, or even haven't heard of it. However, the RESTFul API is already the mainstream mode of opening interfaces in the Internet. Please refer to:

Douban API  https://developers.douban.com/wiki/?title=api_v2

GitHub https://developer.github.com/v3/

    Counting the years, I have been in contact with REST for about 8 years now. You may be very accustomed to accessing the server API directly from the JavaScript client, but 8 years ago, the web was not what it is now. To talk about REST, let's first look at how web clients accessed server interfaces before REST became popular.

    In the early days, before the mobile terminal became popular, the concept of Web API was still very weak. At that time, the website was popular, and it basically followed the back-end-front-end model. The data is generated in the background, and then the data is bound to the front-end HTML code (rendering) in the form of "template". As shown below:

image description

    Then there is the concept of a "domain", and JavaScript can only access servers of the same domain. For example, if we deploy a site under the domain name www.a.com of A, the front-end JavaScript of this site can only access the server whose domain name is www.a.com. What if we need to access other "services" that are not site A? Take a look at the image below:

image description

    The common practice at the time was to use SOAP, the Simple Object Access Protocol, which used XML as a description of the data. Let's look at a solution using SOAP:

image description

    JavaScript cannot directly access the SOAP service. It needs to first access its own website background, and then another website background to access the SOAP service. In addition, the website background and orientation SOAP services in different languages ​​all need to have a "proxy class" that first generates their own specific language, Java has Java, C# has C#, which is quite cumbersome and difficult to understand. At this time, our thinking point comes, what does the background of the website mean to me? Why can't I access the service directly? Why can't I also extract the business code in the website into a service, and finally become the following ideal situation:

image description

    The background of the website is almost a "shell", which is only responsible for static pages such as HTML pages, CSS, and JavaScript files of the website itself. And business logic, just leave it to the service to provide it. The biggest advantage of this is that the business has become independent and can be shared by multiple "websites". Does it feel familiar? This mode is the single-page application made by frameworks such as VUE and AngularJS. However, this model was not popular at the time. I tried this way of thinking to build the web many years ago, but because there is no powerful SPA framework support such as VUE, AngularJS, etc., the effect is not good. However, I believe this neat pattern is the future of the web. I have always advocated simplicity. I lost Flex, Silverlight, ASP.Net WebForm and chose JavaScript because there were too many other packages.

    Many people think that the template engine is a good separation of front-end and back-end, but I don't think so. SPA is the real front-end separation. They use AJax to communicate with each other, and the front-end is the simplest HTML. Front-end developers can see a line of server code. No, this is really nothing to do with language, it is the real front-end and back-end separation.

    Let me analyze why SPA applications were not popular in the past.
    First, one is the deep-rooted thinking of the website;
    second, for performance reasons, frequent Ajax requests on a single page will cause huge pressure on the server. The static technology of website pages is very mature, so the concept of SPA was not advocated very much in the early days. And SPA also has its own limitations, not all websites are suitable for SPA instead. But now the development of server caching technology (especially after the emergence of Memcache and Redis) has greatly solved the problem that the server supports high SPA load, and is even simpler and easier to use than the traditional web page static technology; coupled with the powerful VUE and AngularJS ability, which makes SPA really popular.
    Third, it was not so easy for the front end to access the server across domains at the time. There was no standard specification to define cross domains, and various cross domains were not so easy to use.

    Then I personally think that there are two iconic things that refresh people's understanding of APIs and services: one is the popularity of mobile terminals, and the second is the popularity of REST concepts.
We won't talk about mobile. Let's talk about REST. I personally think that REST is not a technology, but because of its popularity, people gradually accept services as resources, expanding and breaking developers' understanding of the Web.

    Without REST, can clients access services directly across domains? Can. But there is no standard to guide developers how to design API interfaces suitable for services. The popularity of REST, replacing SOAP (which still has a place in some fields), is simple enough, lightweight, and semantically clear enough to fit the age of mobile.

    REST: REpresentational State Transfer, which is translated as "table attribute state transfer". What the hell is this? This is not important, the name originally came from a thesis of a foreign doctor. We mainly need to know that based on the theory in this paper, the interface design style of the RESTFul API is derived.
    Let's take a look at the features of the RESTFul API:

  1. Based on "resources", whether it is data or services, everything is a resource in RESTFul design.
  2. no status. A call generally returns a result, and there is no such situation as "open connection - access data - close connection" that depends on the previous call.
  3. Usually no verbs appear in URLs, only nouns
  4. URL semantics are clear and unambiguous
  5. Use HTTP's GET, POST, DELETE, and PUT to represent additions, deletions, and changes to resources.
  6. Use JSON without XML

    I give an example:
    website: /get_user?id=3
    RESTFul: GET /user/3 (GET is HTTP type)

    Some students may say that I often use GET and POST. But GET and POST in the website are different from GET and POST in RESTFul. The choice of using GET and POST in a website is that GET is used for simple objects and POST is used for complex objects; but in REST, GET corresponds to querying a resource, while POST corresponds to adding a new resource, and the meaning is decidedly different. It is very important to understand this.

    OK, let's move on to some best practice principles for the RESTFul API:

  1. Use HTTP verbs to express adding, deleting, modifying and querying resources, GET: query, POST: add, PUT: update, DELETE: delete
  2. The returned result must be in JSON
  3. HTTP status codes have specific meanings in REST: 200, 201, 202, 204, 400, 401, 403, 500. For example, 401 indicates that the user authentication failed, and 403 indicates that you have passed the authentication, but you cannot operate this resource.
  4. If an error occurs, an error code is returned. For example, I usually define it like this:

image description

  1. API must have the concept of version, v1, v2, v3
  2. Use Token tokens for user identity verification and permission classification instead of cookies.
  3. The url is not case sensitive, do not appear capital letters
  4. Use - instead of _ to do string concatenation in URL paths.
  5. Have a beautiful document~ (very important)

    The above is just a list of some of the practical principles of RESTFul, not all. Given a typical RESTFul API design style:

    https://api.z.cn/v1/product/recent?page=3&size=20

    The above URL is very easy to understand, paging to get the latest Product resources.

    Finally, we want to talk about whether the RESTFul API is easy to use? In some cases it works well, in some cases it doesn't work very well. What works well and what doesn't?
One of my empirical conclusions: For open APIs, Douban, Sina Weibo, and GitHub are easy to use and very suitable; for internal development, it is not easy to use.
    The resource-based RESTFul API interface granularity and return results are too "coarse", and it usually returns a complete data model, which is very unfriendly to clients. But the open API is open because it doesn't know what you need to return the result. Since it doesn't know, then I simply return it to you. The advantage of this is that it is general, but the client is not easy to handle. You only need one field, and the server throws you more than a dozen. As a client developer, what do you think?

    Because the requirements for internal development are very clear, generally speaking, the server should not directly dump resource entities to the client in a simple and rude manner. Can't the RESTFul API be connected to internal development? Of course not, we need to be flexible in designing our internal API by borrowing the advantages of RESTFul. So how to simplify, this is not something that can be explained clearly in an article, and there is no unified standard, you need to ponder and experience it yourself.

    As a final example, I personally will retain most of the REST features when developing internal interfaces, but I will not strictly only write four interfaces: add, delete, modify, and check. Be flexible when necessary. Moreover, the excellent features of error codes and status codes must be retained.

    Well, let's introduce RESTFul here. It is especially emphasized that interface design is a technical task that relies heavily on experience and refactoring. Designing interfaces requires some artist's talent (real experience). You can see that GitHub's interface is very "beautiful". Don't think it's easy, it's really harder than writing code. Don't you think that sometimes it's really hard to come up with a name?

This article was originally published on MOOC.com, please indicate the source for reprinting, thank you for your cooperation!

Reference address: http://www.imooc.com/article/17650

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325299658&siteId=291194637