(turn) design principles for excellent rest-style APIs

Source: Internet
Author: User

Designing a good rest-style API is very difficult! The API is the contract between the service provider and the consumer, and breaking the contract will bring a lot of trouble to the server developers, the trouble comes from the developers who use the API, because changes to the API will cause their mobile app to not work. A good document can do a lot of work to solve these things, but most programmers don't like to write documents.

If you want to make the service side of the value of a better embodiment, you need to design the API. With these APIs, your service/core program will likely become the platform on which other projects depend, and today's big companies: Facebook, Twitter, Google, Github, Amazon, Netflix, and so on. Without a well-designed API to develop their data externally, these companies will not be as powerful as they are today. In fact, the whole industry exists to consume the data provided by the above platform.

The more user-friendly the API you provide, the more people will be willing to use it.

If you are designing the API to follow the principles set forth in this document, the APIs you have designed will make it easier for callers to understand and use, and will significantly reduce the caller's complaints about you; I have described the document content in detail by topic, and readers can choose topics of their own interest without having to read them sequentially.

The terms used in this document and their meanings are as follows:

    • Resource (Resource): A single Instance object, such as animal (an animal); [Carefree Child Note: Roy thomasfielding (the rest-style author) explains the meaning of the resource: A resource can be a document, a picture, A time-related service (e.g. today's weather in Los Angeles) and so on, the resource is the conceptual mapping of the entity, not the entity itself; personal understanding: A picture is a resource, but in my machine there is a real document entity named "Jason.txt", it cannot be called a resource, It is a resource entity, in simple terms: the relationship between a resource and a resource entity is like a class and an object. ]
    • Collection (Collection): A collection is a set of similar instance objects, such as animals (a group of animals).
    • HTTP: A communication protocol transmitted over a network;
    • Consumer (consumer, user): A client program capable of sending HTTP requests; [Carefree Child note: Here Consumer actually refers to the API caller, if the literal translation into the consumer more confusing]
    • Third parties Developer (third-party developers): those developers who are not members of your project project team but want to use your services;
    • Server: An HTTP server/program that can be accessed by consumer over the network;
    • Endpoint (endpoint): a URL provided by the server that identifies a resource (Resource) or collection (Collection); [Carefree Child Note: It is more appropriate to understand the field at the back of the URL, such as url:https:// Api.example.com/vi/zoos's end point is:/zoos;]
    • Idempotent (idempotent): The results of repeated operations are the same;
    • URL Segment (url fragment): A small subset of fragments taken from a URL;

Data design and abstraction

The presentation of the planning API may be simpler than you think, first to determine how your data is designed and how the core program works. It is easier to design an API in a new development project, and if you want to modify an existing project to fit the rest style, you need to work on the abstraction. [Carefree Child Note: According to Roythomas Fielding's design for rest, rest style is more suitable for data-centric architecture rather than a compute-centric architecture]

Sometimes, a collection (Collection) can represent a table in a database, and a resource (Resource) represents a row in a table. [Carefree Child Note: Here the metaphor feels a bit inappropriate, the database row corresponds to a resource entity, not a resource! But most of the situation is not so simple. In fact, your API should be an "as-possible" abstraction of data and business logic. It is very important that complex application data will be difficult for third-party developers to understand and use, and if you do, they will not want to use your API. [Carefree Child Note: When designing an API, the data for parameters and return values should not be too complex, otherwise the developer initiates the call and processes the returned results with a half-day, very troublesome! ]

In some cases, the data of the service cannot be exposed through the API. A common example is that many APIs do not allow third-party developers to create users. [Carefree Child Note: When designing an API, what API is provided when you need to provide what functionality, not too early, too much exposure to unnecessary API interface, we often encounter this situation in the development process: whether it can be used, first of all the functions of their services exposed to say, maybe it is used, It's time to save the changes! ]

Action (Verbs)

You must know the Get and post requests for HTTP, which are the most common requests when accessing various Web pages through a browser. The term post even becomes a common language for people, even if they don't know how the Internet works, they know they can post messages to their friends ' Facebook message boards.

You need to understand the 4.5 very important HTTP actions listed here, 0.5 of which are patches, because it is functionally similar to put, and the remaining 4 are usually used by API developer 22 to use the [carefree child notes: such as Get and post,put and delete]. Here are the actions and their corresponding database calls (I think most developers are more familiar with database operations than the design API). [Carefree Child notes: Formally based on the author's understanding, so many parts of this article is to use the database to explain the API, in fact, this is also very appropriate, because the rest architecture style is resource-based, and the database is a form of resources. In the following explanations, the content in parentheses is a database operation similar to that of the HTTP verb.

    • Get (SELECT): Gets a specified resource or a collection of resources from the server;
    • POST (Create): Creates a resource on the server;
    • PUT (update): Updates a resource on the server and needs to provide the entire resource;
    • PATCH (update): Updates a resource on the server, providing only the part of the attribute that has changed in the resource;
    • Delete: Removes a resource from the server;

There are also two uncommon HTTP actions:

    • head– gets the metadata of a resource, such as a set of hash data or the last time the resource was updated;
    • options– gets the access rights of the current user (Consumer) to the resource;

A good API will take advantage of these 4.5 HTTP actions to allow third-party developers to interact with their own data, and the URLs never contain actions/verbs. [Carefree child Note: The URL is an abstraction of the resource description, the resource description must be a noun, if the introduction of a verb, then the URL represents an action, rather than a resource, which deviates from the rest of the design thought]

Typically, get requests can be cached by the browser (and usually do so), for example, when a user initiates a second post request, the cached GET request (which relies on the cache header) can speed up the user's access. A head request is basically a GET request that has no return body and therefore can be cached.

Version control

No matter what system you are designing, and no matter how much planning you have done in advance, your program will change over time and business, and data relationships may change, and resources might be added or deleted. Developers have to face these problems as long as the software is still alive and someone is using it, especially for API design. [Carefree Child Note: According to Roythomas fielding explanation of the resource: Resource description and resource entity is separate, while the design rest API is based on resource description, when the resource entity changes, as long as modify the resource description and Resource entity mapping, can ensure that the resource description is unchanged, This ensures that the API is not changed and that all third-party programs that use the API do not need to be modified, so the rest style is used to decouple the relationship between this server and the client.]

The API is a contract between the caller (Consumer) and the server, and changing the server's API will inevitably affect its backward compatibility, and the destruction of the contract will incur the complaining of the user (Consumer), and if you change a lot, they may abandon your service. In order to ensure that the server program can evolve and be satisfied with the user, you need to continue to make the older API work while the new version API is introduced.

Note that if you simply add some new features to the API, such as adding new attributes to the resource (these new attributes are not required, they do not work without them), or if you add a new endpoint, you do not need to upgrade the version number of the API, because these changes do not break backwards compatibility. Of course, you still need to update the API design documentation (you and the caller's contract). [Carefree Child notes: The document is too important for the API, no good documents necessarily have no good API, so the API and its documents must be modified synchronously, or even modify the document first]

After a while, you can tell the caller not to recommend (deprecate) using the old version [carefree Child notes: Just like the depredated annotation in Java, used to tell the consumer that I don't recommend using it, I might not be able to support it after a while]. Not recommending an API does not mean shutting it down or reducing its quality of service right away, but telling your API users that they need a version upgrade and that the old version will be stopped after a certain amount of time in the future. [Carefree Child Note: Through the transition period to remind users to upgrade the API, clearly tell the caller what API is in transition period, the transition period of the new and old version can work simultaneously, but the old version will be removed after the transition period]

Adding a version number to the URL is a good API design, and of course another common solution is to put the version number in the request header [Carefree Child Note: HTTP request's Accept field], based on years of experience dealing with third-party developers, I can tell you that placing the version number in the URL is easier to implement and use than it would be in the header of the request. [Carefree Sub Note: There are some questions about this approach, personally understand that the version should identify resources, that is, the version is targeted at the end of the URL endpoint, such as Https://api.example.com/vi/zoos in the/zoos, according to this idea, When a project contains many types of resources that need to be graded for presentation, there may be a number of problems with the version number in the URL, for example: there is an IM for instant Messaging project, which contains user_info (user information), User_rel (user relationship), message three resource class , in which User_info is divided into public and private information privately two types, the type includes a profile of the QR code information self_info,private type including the personal application lock information lock, User_ The rel (user relationship) type includes the friend relationship friends and the group groups two types, groups contains the group member member and the group Info Info two subtype resource, Messge contains the new chat message and the history chat message, These resources are organized into a tree structure as shown in the following:

Assuming that my URL root (the root of the URL will be described later in this article) is: https://test.jason.com/im/*, then the URL for the above resources is:

(1) Https://test.jason.com/im/user_info/public/self_info

The URL represents a resource: User profile of the two-dimensional code information;

(2) Https://test.jason.com/im/user_info/private/lock

The URL represents a resource: The user's app lock information;

(3) Https://test.jason.com/im/user_rel/friends

The URL represents a resource: The user's friend information

(4) Https://test.jason.com/im/user_rel/groups/member

The URL represents a resource: A group member of a group

(5) Https://test.jason.com/im/user_rel/groups/info

The URL represents a resource: group information

(6) Https://test.jason.com/im/message/new

The URL represents a resource: A user's new chat message

(7) Https://test.jason.com/im/message/history

The URL represents a resource: A user's history chat message

The question is: In this case, where should the version number be placed in the URL?

If the version number is for the IM entire project, for example, here the IM project is divided into V1 and v2 two large versions, at this point the URL header can be changed to: https://test.jason.com/im/v1/*,https://test.jason.com/im/ v2/*, the actual URL resource will become: Https://test.jason.com/im/v1/message/new.

If the version number is for a subclass of an IM project, for example, where the message type is divided into V1 and v2 two versions, the URL root of the messaging class becomes: https://test.jason.com/im/message/v1/*,https:// test.jason.com/im/message/v2/*, the actual URL resource will become: Https://test.jason.com/im/message/v1/new.

If the version number is more detailed for the resource type, then the version number is later. In some responsible types of projects, the types of resources are also very complex and hierarchical, and it is difficult to determine the location of the V1 as recommended by the authors of this article]

Analysis

Keep track of how the API for each version/endpoint is called [Carefree child Note: This shows that the version number corresponds to the "endpoint" at the end of the URL.) By adding a counter to each API in the database, the corresponding usage count is incremented by 1 for one request. There are many benefits to counting the invocation of each API, such as optimizing the API with the highest frequency of calls.

In order to build the API that third-party developers like, the most important thing is to determine when not to recommend (deprecate) users to use the old version of the API, you can use these non-recommended (deprecated) APIs to inform third-party developers, This is a good way to remind them before you discard the old version.

The process of notifying third-party developers can be automated, for example, by sending an e-mail alert to the appropriate developer for each call to the deprecated API 10,000 times.

The root URL of the API

Whether you believe it or not, the root design of the API is very important. When a developer takes over an old project developed using your API and needs to add new features to it, he may not know your service at all, and perhaps they know the list of URLs that are being called. The important thing is that the URL root of your API should be as simple as possible, and a long, complex URL looks scary, and it's likely to scare these third-party developers away.

Here are two common URL roots:

    • https//example.org/api/vi/*
    • https//example.com/vi/*

If your application is large, or it may become very large in the future, you can put the API in their own subdomain, so that your program in the future development of more flexible and easier to expand. [Carefree Child Note: Here the author would like to express the meaning of the URL represents the resources to classify, hierarchical, different resources in different classes]

If your program doesn't get that big, or if you want to simplify the use of your program (for example, if you want to provide both Web sites and API services through a framework), put your API behind the URL's root domain (for example:/api/).

It's best to let your API's root also contain content. For example, access to the root of Githubapi gets a list of endpoints (endpoints represent resources). I prefer to use the root URL for information that is useful for developers who are confused, such as how to get the developer documentation for the API.

Note Using the HTTPS prefix, a good restfulapi must use HTTPS as the prefix. [Carefree Child notes: For example: Https://api.example.com/v1/zoos]

Endpoint

An endpoint is the part of a URL fragment that identifies a specific resource or collection of resources. [Carefree Child notes: For example: Https://api.example.com/v1/zoos in/zoos]

If you want to build an API to represent multiple zoo resources, where each zoo contains many animals (each animal can only belong to one zoo), the operator (who works in multiple zoos), and needs to track the details of each animal, the endpoints of these APIs might look like this: [ Carefree Child Note: The following URL in red bold suffix is the end point]

    • Https://api.example.com/v1/zoos
    • Https://api.example.com/v1/animals
    • Https://api.example.com/v1/animal_types
    • Https://api.example.com/v1/employees

When you describe the effects of these endpoints, you need to give these endpoints and the HTTP actions to manipulate them. For example, given below is the function of the list of zoo APIs just built, note that I have added HTTP actions to each endpoint, just like the one used in the HTTP request.

  • Get/zoos: List all the zoos (including the zoo's ID, name and profile);
  • Post/zoos: Create a new Zoo;
  • Get/zoos/zid: Get a complete zoo object; [Carefree child Note: The Zoo object here refers only to "zoo", such as "Zoo" ID, name, Introduction and other information, not including the zoo's animals, employees and other types of information]
  • Put/zoos/zid: Update an Animal object (all information included);
  • Patch/zoos/zid: Updating an Animal object (contains some information);
  • Delete/zoos/zid: Delete a Zoo object;
  • Get/zoos/zid/animals: Get all the animal information (including the animal ID and name) of the designated zoo;
  • Get/animals: Refers to the listing of all animal information;
  • Post/animals: Create a new animal;
  • Get/animals/aid: Get the object information of an animal;
  • Put/animals/aid: Update an animal's object information (providing the entire contents of the object);
  • Patch/animals/aid: Update an animal's object information (to provide part of the object's content);
  • Get/animal_types: Access to all animal type information;
  • Get/animal_types/atid: Gets the type description information of the specified animal type;
  • Get/employees: Get a list of all employees;
  • Get/employees/eid: Gets the information of a specified employee;
  • Get/zoos/zid/employees: Get a list of all employees of the specified zoo;
  • Post/employees: Create a new employee;
  • Post/zoos/zid/employees: An additional employee for the designated zoo;
  • Delete/zoos/zid/employees/eid: Dismissal of an employee of a designated zoo;

In the list above, Zid indicates that the zoo's id,aid indicates that the animal Id,eid indicates that the employee Id,atid the animal type ID, giving the keyword and meaning in the document a very good habit.

In the example above, I have briefly listed the URL prefixes for common APIs, a simplification (omitting URL prefixes) that is very useful for communication, but in your API documentation, you still want to use all the URLs (for example: GET https://api.example.com/vi/ Animal_type/atid). [Carefree Sub-note: In an informal document to introduce an API can take the endpoint instead of the completion of the URL method: HTTP action + endpoint + The endpoint of the function description, the endpoint is much shorter than the full URL, so easier to express, and does not affect the understanding, but in the official document still want to write the URL full]

There is a need to pay attention to the presentation of relationships between data, especially the many-to-many relationships between employees and zoos. You can represent more data relationships by adding URLs [carefree child notes: According to Roythomas Fielding's interpretation of resources, relationships are also a resource, so when you encounter many-to-many data relationships, you can split the data relationship and add a URL for each relationship]. Of course, there is not an HTTP operation to dismiss an employee, but we can achieve the same effect by deleting the employee of the specified zoo. [Carefree Child Note: This is an explanation of the article "Delete/zoos/zid/employees/eid: Dismissal of an employee of a designated zoo" above]

Filter filters

When a user requests to get a list of objects, you need to filter the results and return a set of objects that are strictly user-compliant. Sometimes the number of returned results can be very large, but you also cannot arbitrarily constrain this, because the arbitrary constraints on the server side can cause confusion for third-party developers. If a user requests a collection and iterates over the returned results, then as long as the first 100 objects are required, then the user is asked to indicate the limit. So users will not have such doubts: is their program bugs or the interface limit of 100? Or is the network only allowed to send such a large package? [Carefree Child Note: There is an interface in the IM project to let the user pull their own historical messages, we need to add a parameter in the interface to let the user determine how many historical messages this secondary pull, the server side based on the user's incoming limit amount to determine the number of returned messages, Instead of being implemented by the server, it is determined that the interface can only return a few calls at a time.

Minimize arbitrary constraints on third-party developers. [Carefree Child Note: Do not add default constraints in the interface]

A very important point: let third-party developers specify the constraints of the sort filter/return result set themselves. The most important reason to do this is: users can use as little network consumption as possible to obtain the results; The second important reason is that the user may be lazy, want the server to help them do paging and filtering, and a less important to the client, but it is important for the server: Doing so will reduce the requested resource load.

Filters are typically used to filter the collection of resources returned by a GET request, and filter information can be passed through a URL in a GET request. You can safely apply the filter types listed in the following example to your own API:

    • LIMIT=10: Limit the number of result sets returned to the user (usually for paging);
    • OFFSET=10: Returns a result set to the user (usually for paging); [Carefree Child Note: Specify an offset, starting from the specified position to return a result set, with the limit used to achieve the paging effect, the first time to get the specified number of results from the beginning, followed by the return from the last result]
    • Animal_type_id=1: Returns a qualifying result set (similar to a where query condition for a database: where animal_type_id=1);
    • SORTBY=NAME&ORDER=ASC: Sorts the result set by the specified attribute and the specified sort (similar to the data's order by name ASC);

Some of the above filters are duplicated with some of the URL endpoint features described earlier, such as the previously mentioned url:get/zoo/zid/animals that are functionally duplicated with Get/animals?zoo_id=zid using filters. A single endpoint is easier for third-party developers, especially if they use the requests you provide to do some complex development. Explicitly writing out the repeated requests for these features in the API documentation will eliminate the confusion of third-party developers about these repetitive functions, or they will wonder if there is a difference between these repetitive features!

Also, when you need to filter or sort the data, you want to list the third-party developers (Consumer) which properties can be used for filtering or sorting, and we don't want to return any errors of database operations to the user. [Carefree Child Note: Do not expose errors or problems within the service to third-party developers]

Status code

Taking full advantage of the appropriate status code is important for designing RESTful APIs because HTTP status codes are already standard defined and can be read and recognized by various network devices. For example, by configuring the load balancer's parameters to avoid sending the request to a service program that appears with a 50X error [Carefree child Note: 50X indicates an internal error in the service program]. Here are some of the HTTP status codes that you can choose to use, which can be the starting point for your well-designed return code:

    • Ok–[get]

When the client requests data from the server, the server locates the data and returns it to the client (the power of this behavior); [Carefree Child note: Get operation can only fetch data (that is, read only), should not make any kind of modification to the server's data]

    • 201 Created–[post/put/patch]

The client sends data to the server, and the server creates a resource for the data;

    • 204 NO Content–[delete]

When a client requests the server to delete a resource, the server deletes the resource; [Carefree Child Note: Return code 204 indicates that the execution was successful, but there is no data. The description of the 204 return code in HTTP RFC2616 is: If the client is a proxy (such as a browser), it should not change the "trigger this Request" page display, the return value is mainly used when the input behavior occurs, although the new or updated metadata information is applied to the current page, However, the agent (browser) can not change the current page display, the original text is:

If the client is a user agent, the itshould isn't change it document view from this which caused the request to besent. This response was primarily intended to allow input for actions to takeplace without causing a change to the user agent s a Ctive Document View,although Any new or updated metainformation should being applied to the documentcurrently in the user age NT ' s active view.]

    • INVALID Request–[post/put/patch]

The client sends an invalid request to the server, and the server does nothing about it (this behavior is idempotent).

    • 404 Not found–[*]

The client requested a resource or resource collection that does not exist, and the server does not make any action on it (This behavior is idempotent).

    • INTERNAL SERVER error–[*]

An error has occurred inside the server and the client cannot know whether the request was executed successfully.

Status Code Range

The return code of 1XX is reserved for the underlying use of HTTP and will not be actively sent in your entire career.

A return code of 2XX indicates that the request was executed as expected and the information was returned successfully. The service side wants to return this result to the user as much as possible.

A return code of 3XX indicates a request redirection, and most APIs do not frequently use this request (), but the latest Hypermedia API makes full use of these features.

The return code of the 4XX mainly represents errors caused by the client, such as request parameter error or access to a nonexistent resource, these must be idempotent operations, and cannot change the state of the server [Carefree child Note: In fact, the state of the server changes means that the operation is not idempotent].

The return code of the 5XX mainly indicates errors caused by the server, and usually these errors are thrown by the underlying function that the developer ([Xiaoyao Note: This should be the developer of the server program]) is not exposed to, and then passed to the user ([Xiaoyao Note: This should be a third-party developer]). When a user receives a return code of 5XX, they do not know whether the server is currently working properly, so try to avoid this situation.

Return value Document

When third-party developers send HTTP requests, they need to know the return value information for these requests in advance, and the following list is some rest-style APIs and their corresponding return value information: [Carefree Child Note: Similar to the previous Introduction URL function, Just here to replace the last URL description with the return value description, which still uses the three-segment Description method: HTTP request action + endpoint + endpoint corresponding return value description information]

    • Get/collection: Returns a list of resource objects;
    • Get/collection/resource: Returns a resource object;
    • Post/collection: Returns the newly created resource object
    • Put/collection/resource: Returns a complete resource object;
    • Patch/collection/resource: Returns a complete resource object; [Carefree Child Note: Although the content of only a subset of the resource object is in the request, the content returned is the entire resource object]
    • Delete/collection/resource: Returns an empty document;

It is important to note that when a user creates a resource, they usually do not want to know the ID of the newly created resource (nor do they want to know other properties such as modified or created timestamp) [Carefree Child Note: This is a bit confusing, this design idea should also be differentiated, if the resources are very complex, this article introduced this idea may be feasible , if the resource is inherently simple, such as the Send Message interface we designed previously, the user is returned the ID of the message sent directly. These new attribute information can be obtained from subsequent requests, but can also be returned by initializing the POST request.

Authorized

In most cases, the server wants to know exactly who the initiator of each request is? Of course, some API interfaces can be released with anonymous access, but usually the interface can only be accessed by authorized users.

OAUTH2.0 provides a good way to achieve this. Can you tell which client initiated each request? Which users are represented behind these requests? As well as providing a standardized user access or revocation access, all without the need for a third-party user's login to credit.

There are also OAuth1.0 and Xauth that can perform similar functions. Regardless of that approach, it is important to ensure commonality and good document design, in the documentation of the user's common language/platform in a variety of different packaging libraries detailed description. [Carefree Child Note: These services are used as libraries for client calls, such as the SDK, so you will have a detailed description of the various forms of encapsulation libraries in the documentation]

I can tell you truthfully that although oauth1.0a is the safest option, it is very hard to deploy. I met a lot of third-party developers complaining that they had to implement their own libraries because oauth1.0a didn't have libraries for the languages they used. I spent a lot of time addressing the incomprehensible "invalid signature" errors. Therefore, I recommend that you use a different alternative.

Content Type

Most of the rest-style API interfaces now provide JSON-formatted data, as you can remember from Facebook, Twitter, and GitHub. XML has gradually dropped out of view (except for some large companies that are still in use), thanks to the fact that the SOAP method has disappeared, and we have not seen the API interface to return the HTML format data.

The developer language or framework commonly used by developers can easily parse the various valid data you return. If you are using a different serializer to build a generic return object, you can use any of the preceding data formats (except SOAP), but you need to be careful when returning data to handle the Accept field of the request header. [Carefree Child Note: The HTTP request header's accept can be used to specify the format of the returned data]

Some API developers recommend adding an extension field for a URL (after the endpoint) for different types of returned content. For example:. Json,.xml, or. html, but I do not recommend this, I recommend using the HTTP request header's Accept field (the HTTP RFC has an explanation of the accept), and think that this is the appropriate method.

Hyper Media API

The Hypermedia API may represent the future of the rest-style API, which is more in line with the design of HTTP and HTML. [Carefree Child notes: According to rest author Roy Thomas Fielding, rest core is resource-oriented design, Hypermedia Services provides access to a variety of multimedia resources, which in essence conforms to the resource-centric design]

When using a non-hypermedia rest-style API, the URL endpoint is also part of the contract between the client and the server, which must inform the client beforehand that the client cannot interact with the server as expected once it is changed, which is actually a constraint.

Now, the user of the API is more than just the user agent who can initiate HTTP requests, and the browser initiates HTTP requests more often. However, users are not constrained by the URL endpoints of these pre-defined, restful APIs. What makes a user so special? Now the Web page allows users to read the topic first, and then click on the topic they are interested in the corresponding link, access to the site they want to visit or want to read the content, when the URL changes, the user is not affected (unless the user tagged a page, when they visit these tagged pages will automatically jump to the home page, Users need to find new paths to the data they are interested in from the home page. [Carefree Child Note: Our site is usually used this way, especially for various portals, such as NetEase: www.163.com, Sina: www.sina.com, open These portals, we do not see a URL, we see a theme, each subject to a hyperlink (URL), when these topics corresponding to the URL changes, only need to adjust the theme and hyperlink (URL) mapping relationship, users actually do not see the changes in these URLs Of

The Hypermedia API concept is similar to the behavior of an ordinary person. The root directory of the request API will get a list of URLs, each of which may correspond to a set of information, and it describes the collection of information in a way that the user can understand. There is no need to provide an ID for each resource (unless specifically invited), because a URL uniquely identifies a resource.

When the Hypermedia API user accesses the connection and collects information, the returned results are placed in the most recently updated URL link, so the URL does not have to be agreed with the user beforehand. If the URL is cached, subsequent requests return to 404[: 404 means that a nonexistent resource was requested] and the user simply goes back to the root directory to find the content again.

When retrieving a list of resources from the collection, return the full URL of the resource list to the user. When a post/patch/put request is executed, a response with a return code of 3XX is used to redirect to the new resource.

JSON does not provide us with the semantics needed to indicate which properties are URLs or how URLs are associated with the current document, and perhaps, as you might guess, HTML can provide such information. We can get the data through the API first, then HTML processing. Think of the way that CSS accompanies us, and we may one day see that the same approach is used both for API requests and for site access, both for the same URL and content. [Carefree Child Note: JSON provides data content, does not provide data presentation capabilities]

Document

To be honest, your API won't necessarily be too bad if you don't follow this document completely, but if you don't write the right documentation for the API, no one will want to use it, it will become an extremely difficult API.

Make sure your documents are accessible to developers without authorization.

Do not use automatic document generator, if used, you must carefully review and modify the generated documents, to ensure that they can be understood and used by the user.

The request and response package in the example in the document is written in full, do not truncate the unimportant part, but highlight the important part.

What are the possible causes of the expected return codes and possible error messages for each URL endpoint in the document?

If you have enough time, you can also build an API console used by third-party developers so that they can immediately validate your API. This will not be as difficult as you might think, but developers, including internal developers and third-party developers, may prefer to use your API for this feature.

Make sure that the document is printed, for example, that CSS is a powerful way to display documents, and that you must hide the document's toolbars when the document is printed, even if no one prints your document with a printer, and many developers like to export them as PDFs for offline viewing.

Original stickers: 54315835

(turn) design principles for excellent rest-style APIs

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.