A brief talk on RESTful API

Source: Internet
Author: User
Tags representational state transfer

In the first half of the year, the Department organized a discussion on the technical topics of practice microservices, the main content of which is the advantages and difficulties of SOA services and microservices, including the design methodology for restful APIs.

Just recently in-depth study of the HTTP protocol, but also read some information about the RESTful API, this blog, will be some of their own understanding of the record.

PS: This blog mainly talk about some summary of the design ideas and methods, do not talk about specific implementation details, such as the error is welcome to point out, thank you!

To learn more about the restful API, it is recommended to learn some of the terms listed below:

HTTP protocol, Distributed System Architecture principles (CAPS), operating system principles ...

Resources:

Follow GitHub to learn testful HTTP API design

A convention for RESTful API interfaces

RESTful API Design Best Practices

Know: How to explain restful APIs in plain language?

First, the Origin of rest

Full name: REST, full name is resource representational state Transfer, namely: the resources in the network in some form to carry on the status transfer . ———— the so-called state of the transfer, you can refer to the "HTTP authoritative guide" in the Book of the detailed interpretation of the agreement, but here is more than repeat!

Appeared: Rest was first mentioned in a paper published by Dr. Roy Fielding, who was also involved in the design of the HTTP protocol. Paper Address: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

Definition: In simple terms, rest is a system architecture design style (not standard), a Distributed System Application layer solution.

Background: The early Web page is the front and back together, such as PHP, JSP and so on. With the rapid development of mobile terminal in recent years and the application of distributed architecture, a variety of clients, this time need to have a unified mechanism to provide services for the front-end communication.

The RESTful API is one of the more mature application API design theories.

Objective: To further decouple the client and server side.

Application: The most classic is the GitHub API.

Ii. characteristics and advantages of restful

1. Client-server (client-server): The server that provides the service and the client that uses the service detach decouple;

Advantages: Improve the convenience of the client (simple operation)

Simplify servers for scalability (high performance, low cost)

Allow client server-side teaming optimizations that are unaffected by each other

2, stateless (stateless): Each request from the customer must contain all the information required by the server to process the request (Request information uniqueness);

Pros: Increased visibility (each request can be considered separately)

Increased reliability (more prone to failure recovery)

Increased scalability (reduced server resource usage)

3, cacheable (cachable): The server must let the client know if the request can be cached? If possible, the client can reuse the previous request information to send the request;

Pros: Reduce the number of interactive connections

Reduce network latency in the connection process

4, layered system (layered systems): Allow the server and the client middle tier (proxy, Gateway, etc.) in place of the server to respond to the client's request, and the client does not need to care about the components interacting with it;

Advantages: Improved scalability of the system

Simplifies the complexity of the system

5. Unified Interface (Uniform Interface): The method of communication between customer and server must be unified. (Example: Get,post,put. DELETE)

Benefits: Improved visibility of interactions

Encourage individual optimizations to improve components

6. Support on-demand code (Code-on-demand, optional): The server can provide some code or script and execute it in the client's running environment.

Benefits: Improved Scalability

Three, outline design method

1. Agreement

API and Client communication protocol, always use the HTTPS protocol.

PS: Using the HTTPS protocol does not have much to do with the RESTful API itself, but it is important to increase the security of your site, especially if you are providing an open API, which is more important than HTTPS.

2. Domain Name

You should try to deploy the API under a dedicated domain name, such as:

https://api.github.com

If the API changes significantly, you can design the API as a subdomain, such as:

https://example.com/api/v1

3. Version (Versioning)

In general, the API should be put into URLs, such as:

https://example.com/api/v1

You can also put the version number in the HTTP information header, but it is not as convenient and intuitive to put in the URL.

4. Path (Endpoint)

In the protocol, each URL represents a storage address of a resource, so the URL can not have verbs, only nouns, and nouns should generally correspond to the table field of the database, and the API nouns should use complex numbers. For example:

/users/:username/repos/users/:org/repos/repos/:owner/: Repo/repos/:owner/:repo/  Tags/repos/:owner/:repo/branches/:branch

PS: According to RFC3986 definition, the URL is case-sensitive, so should try to use lowercase letters to name!

5, Methods (method)

With the URL design of the resource, all operations against the resource are specified using the HTTP method, and the common methods are the corresponding SQL commands in parentheses:

verd
head (SELECT)
get (SELECT) get resources
post (Create) Create Build Resources
patch (update) Update the partial properties of the resource (very Less, usually with post instead)
put (update) update Source, the client needs to provide all the properties of the new resource
delete (DELETE) Delete resource

Like what:

Get/user: List All users post/user: Create a new user patch/user/id: Update information for a specified user delete/user/id: Delete all Users

6. Data Filtering (Filtering)

If the amount of data is too large, the server cannot return all the data to the user. The API should provide parameters (such as query) to filter the returned results. Like what:

limit=10: Specify the number of records to return ? offset=10: Specifies the start position of the returned record ? page=2&per_page=100: Specify the number of pages, and how many records per page ? sortby=name&order=ASC: Specifies which property is the return result sorted by, and sort order ? State=close: Specify filter criteria

7. Status Code

In the HTTP message composition, it is important to have a field: status code. It indicates the approximate condition of the request, whether it is handled properly, what errors have occurred, etc. Status codes are three-bit numbers and are roughly divided into several intervals:

Status code Describe
2XX Request normal processing and return
3XX Redirect, the requested resource location has changed
4XX The client sent the request in error
5XX Server-Side errors

About the status code, the specific introduction can go to my previous blog HTTP status code or reference other materials, here not too much to repeat.

8. Error handling

In the case of an error, the response body should be given a clear error message in the form of a key-value pair, using the Message field.

The basic idea should be to provide as much accurate error information as possible, such as incorrect data format, missing a field ... Instead of just saying "request Error".

9. Hypermedia API

Restful APIs are best designed to be hypermedia: provide links to related resources in the returned results, and connect to other API methods so that users do not need to look up documents and know what to do next.

The advantage of this is that the user can get the address that needs to be accessed by subsequent operations based on the returned results.

10. Identity Verification

In general, it is bad practice for anyone to have random access to the public API, and authentication and authorization are two things:

Verification (authentication): Determine the user's stated identity, such as providing the password for the account. Otherwise, it is very dangerous for anyone to forge other identities (such as other users or administrators);

Authorization (Authorization): guarantees that a user has permission to request a resource-specific action. For example, the user's private information can only be accessed by themselves, others cannot see it, some special operations can only be operated by the administrator, other users have read-only permissions, and so on.

If you do not pass the verification, you need to return 4unauthorized status code, and in the body to describe the specific error message, and no authorized access to the resource operation, you need to return 403 Forbidden status code, and detailed error information.

PS: Github API returns 404 Not Found for resource operations that some users have not been granted access to, in order to prevent the disclosure of private resources (such as hackers can automatically test the user's private resources, return 403, is tantamount to telling the hacker user to have these private resources).

11. Writing Documents

The API is ultimately designed for use by people, both internally and externally, and, despite all the rules mentioned above, API design is elegant, but sometimes users do not know how to use the provided APIs.

Therefore, it is necessary to write clearly readable documents.

And writing documents can also be used as a part of the output, as well as to make records to facilitate query reference.

The above content for my personal collation of the summary of the RESTful API, interested in children's shoes can be self-access to other information, this blog does not guarantee the full correctness of the content!

A brief talk on RESTful API

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.