Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the RESTful API design method?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "what is the design method of RESTful API". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. Agreement

The communication protocol between API and users always uses the HTTPs protocol.

Second, domain name

API should be deployed under a dedicated domain name as much as possible.

If you determine that the API is simple and there will be no further extension, consider putting it under the primary domain name.

III. Version (Versioning)

You should put the version number of API in URL.

Another approach is to put the version number in the HTTP header, but it is not as convenient and intuitive as putting it in URL. Github adopts this approach.

4. Path (Endpoint)

The path, also known as "endpoint", represents the specific URL of the API.

In RESTful architecture, each URL represents a resource, so there can be no verbs in the URL, only nouns, and the nouns used often correspond to the table names of the database. In general, tables in a database are "collection" of the same record, so nouns in API should also be plural.

5. HTTP verbs

For the specific operation type of the resource, it is indicated by the HTTP verb.

There are five commonly used HTTP verbs (the corresponding SQL command in parentheses).

GET (SELECT): fetch a resource (one or more) from the server.

POST (CREATE): create a new resource on the server.

PUT (UPDATE): updates the resource on the server (the client provides the full resource after the change).

PATCH (UPDATE): updates the resource on the server (the client provides changed properties).

DELETE (DELETE): removes resources from the server.

There are also two less commonly used HTTP verbs.

HEAD: gets the metadata of the resource.

OPTIONS: get information about which properties of the resource can be changed by the client.

Here are some examples.

GET / zoos: list all zoos

POST / zoos: create a new zoo

GET / zoos/ID: get information about a designated zoo

PUT / zoos/ID: update information about a designated zoo (provide all information about the zoo)

PATCH / zoos/ID: update information about a designated zoo (provide some information about the zoo)

DELETE / zoos/ID: delete a zoo

GET / zoos/ID/animals: list all animals in a specified zoo

DELETE / zoos/ID/animals/ID: deletes a specified animal from a specified zoo

VI. Filter information (Filtering)

If there are a large number of records, it is impossible for the server to return all of them to the user. API should provide parameters to filter the returned results.

Here are some common parameters.

? limit=10: specifies the number of records returned

? offset=10: specifies the starting position of the returned record.

Page=2&per_page=100: specify the number of pages and the number of records per page.

Sortby=name&order=asc: specifies the property by which the returned results are sorted, and the sort order.

? animal_type_id=1: specify filter criteria

Parameters are designed to allow redundancy, that is, to allow occasional duplication of API paths and URL parameters. For example, GET / zoo/ID/animals and GET / animals?zoo_id=ID have the same meaning.

7. Status code (Status Codes)

Some of the status codes and prompts returned by the server to the user are as follows (square brackets are the HTTP verbs corresponding to the status code).

200 OK-[GET]: the server successfully returned the data requested by the user, which is idempotent (Idempotent).

201 CREATED-[POST/PUT/PATCH]: the user created or modified data successfully.

202 Accepted-[*]: indicates that a request has entered the background queue (asynchronous task)

204NO CONTENT-[DELETE]: user deleted data successfully.

400 INVALID REQUEST-[POST/PUT/PATCH]: the request made by the user is incorrect and the server does not create or modify data, which is idempotent.

Unauthorized-[*]: indicates that the user does not have permissions (token, user name, password error).

Forbidden-[*] indicates that the user is authorized (as opposed to the 401 error), but access is prohibited.

404 NOT FOUND-[*]: the request made by the user is for a record that does not exist, and the server does not operate, which is idempotent.

Not Acceptable-[GET]: the format of the user request is not available (for example, the user requests the JSON format, but only the XML format).

410 Gone-[GET]: the resource requested by the user is permanently deleted and will not be obtained again.

422 Unprocesable entity-[POST/PUT/PATCH] A validation error occurred while creating an object.

500 INTERNAL SERVER ERROR-[*]: an error occurred on the server and the user will not be able to determine whether the request was successful or not.

For a complete list of status codes, see here.

8. Error handling (Error handling)

If the status code is 4xx, the error message should be returned to the user. Generally speaking, error is used as the key name and error information as the key value in the returned information.

{

Error: "Invalid API key"

}

IX. Return the result

For different operations, the results returned by the server to the user should conform to the following specifications.

GET / collection: returns a list of resource objects (array)

GET / collection/resource: returns a single resource object

POST / collection: returns the newly generated resource object

PUT / collection/resource: returns the complete resource object

PATCH / collection/resource: returns the complete resource object

DELETE / collection/resource: returns an empty document

10. Hypermedia API

It is best for RESTful API to be Hypermedia, that is, to provide links in the returned results to other API methods, so that the user knows what to do next without looking up the document.

For example, when a user makes a request to the root of api.example.com, he or she will get such a document.

{"link": {

"rel": "collection https://www.example.com/zoos","

"href": "https://api.example.com/zoos","

"title": "List of zoos"

"type": "application/vnd.yourformat+json"

}}

The above code indicates that there is a link attribute in the document, and the user will know what API to call next by reading this attribute. Rel indicates the relationship between the API and the current URL (collection relationship, and gives the URL of the collection), href represents the path of the API, title represents the title of the API, and type indicates the return type.

The design of Hypermedia API is called HATEOAS. Github's API is designed in this way, and visiting api.github.com results in a list of all available API URLs.

{

"current_user_url": "https://api.github.com/user","

"authorizations_url": "https://api.github.com/authorizations","

/ /...

}

As you can see from the above, if you want to get information about the current user, you should visit api.github.com/user and get the following result.

{

"message": "Requires authentication"

"documentation_url": "https://developer.github.com/v3""

}

The above code indicates that the server gives the prompt information, as well as the URL of the document.

11. Other

(1) API authentication should use OAuth 2.0 framework.

(2) the data format returned by the server should use JSON as much as possible and avoid using XML.

This is the end of the content of "what is the Design method of RESTful API". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report