当前位置:网站首页>Analysis of open API design specification

Analysis of open API design specification

2022-06-23 07:44:00 Xujingfeng

background

Recently due to business needs , The system I am responsible for needs to be opened to the outside world Open API, It was not a difficult thing , Because Alibaba cloud's internal Open API The open mechanism is very mature , I don't need to design at all , But this time the demand is mainly for some reasons , You need to design some specifications yourself , That means , Need to be right Open API Make some specification constraints , So there is this article .

Open API Just like the front page , It has always been the facade of the product , Open API No specification , It will reduce the professionalism of the product . In the cloud scene , Many users will choose to build their own portal , Docking with cloud products Open API, The demand for us is to build a mature Open API Mechanism .

From a business point of view , There are some guidelines , Guide us to improve Open API Mechanism :

  • The interface used by the front page and Open API The interfaces provided are the same set of interfaces
  • Any front-end page interface should have a corresponding Open API

From a technical point of view , There are a lot of API Open standards for our reference , Some open source products Open API The documentation is also very complete . One side , I will take its essence , On the other hand , We should consider the particularity of our own product output form . This article will focus on many factors , Try to find a suitable Open API Open specification .

Open API Design considerations

A perfect Open API What should be regulated in the end ?

From a design point of view , You need to consider : Naming specification , Constitute a norm , Path specification , Access specifications , Data type specification , Unified return value specification , Error code specification , Paging specification .

From a team perspective , Whether the team has enough experience in back-end primary and intermediate development and front-end R & D , Understand and implement well formulated API standard . meanwhile , With the flow of people , This Open API Whether the norms can be passed down well .

From the perspective of the industry , Need to consider providing Open API Whether the market in which your product is located is mature ,API Styles may already have corresponding specifications .

From the product point of view , Each product is suitable for API The style is different , This perspective will be discussed in the following paragraphs .

All in all ,Open API The design of is a thing that is difficult to form a conclusion , I'm introducing what my product will eventually adopt Open API Before the specification , Let's talk about some familiar concepts first , for example restful.

restful The dispute over norms

Where there are people, there will be Jianghu .

The same is true where there is code .

If you're in the code circle , I must have heard of restful standard :

  • The addition, deletion, modification and query shall be declared as :POST、DELETE、PUT、PATCH、GET

  • There should be no verbs , Verbs are unified by HTTP Method Express

  • It shows “ resources ” The abstraction of

  • utilize pathVariable,queryParam,header,statusCode Express a lot of business semantics

restful Norms seem beautiful , But if you've really tried landing , There must be some similar problems :

  • Take the user login interface as an example , Such interfaces are difficult to map to the addition, deletion, modification and query of resources
  • To query the most recent 7 For example, the error rate of interface requests within hours , Derived to such as graphQL Such complex query scenarios , Often need to json structure ,GET This cannot be achieved , Only POST To deliver

Based on this ,restful Gradually, there are voices of opposition to the norms :

  • Force everything to “ resources ” Melt it , Contrary to development common sense , Not all interfaces can be mapped by simply adding, deleting, modifying, and querying
  • Complex query semantics may not be available GET expression

restful A fan of style , There is no shortage of attacks against these opposition remarks , There are inevitably “ Refuse restful The style is mainly composed of low-level architects and front-end and back-end programmers , Not designing is a human problem , It's not a matter of norms ” Such remarks . At the same time restful Sublimation : The retrieval of complex parameters , stay restful In semantics, it should be classified as post, Because this behavior is not the positioning of resources (GET), But the retrieval of resources (POST)

This obviously stimulated restful The nerves of style opponents , Disdain to say : o , foolish restful Fundamentalists .

I didn't know you were restful A supporter or an opponent of ? Or is it , Neutrals .

restful This is the end of the dispute , This argument is pure fiction , Officials don't have to worry about . No matter what you think restful, Here is my discussion , You can be a neutral , Otherwise, the effect will be halved .

ROA And RPC

API Design is not just restful A specification , In a larger perspective , Mainstream API Design style can be divided into

  • Resource oriented design , namely ROA(Resource oriented architecture)
  • Process oriented design , namely RPC(Remote Procedure Call)

restful That is ROA A typical example of style , and RPC Style is relatively not easy to be known , But in fact, the interface of most systems is RPC Style , It's just RPC The concept of style is not well known .

In the form of a user module CRUD For example , Compare the next two styles :

ROA style

Create user (POST)

1
2
3
4
5
6
7
8
9
Request:
POST /users

{"name": "kirito", "age": 18}

Response:
HTTP 201 Created

{"id": 1, "name": "kirito", "age": 18}

Query the user (GET)

1
2
3
4
5
6
7
Request:
GET /users/1

Response:
HTTP 200 OK

{"id": 1, "name": "kirito", "age": 18}

Query user list (GET)

1
2
3
4
5
6
7
Request:
GET /users

Response:
HTTP 200 OK

{[{"id": 1, "name": "kirito", "age": 18}], "next": "/users?offset=1"}

establish / Modify the user (PUT)

1
2
3
4
5
6
7
8
9
Request:
PUT /users/1

{"name": "kirito", "age": 19}

Response:
HTTP 200 OK

{"id": 1, "name": "kirito", "age": 19}

Modify the user (PATCH)

1
2
3
4
5
6
7
8
9
Request:
PATCH /users/1

{"age": 20}

Response:
HTTP 200 OK

{"id": 1, "name": "kirito", "age": 20}

Delete user (DELETE)

1
2
3
4
5
Request:
DELETE /users/1

Response:
HTTP 204 No Content

ROA Style and restful The specification says the same thing , To facilitate its connection with RPC Comparison of style interface , Here are some interesting points of the above example :

  • Use HTTP Response code (200,201,204), complete HTTP Mapping between semantics and business semantics , Abnormal flow also occurs 404,401 , etc. ( For the sake of space , This article does not introduce exception flow )
  • PATCH Partial modification of resources , The request body is the content of the modified part ;PUT establish / Modify resources , The request body is the entire content of the new resource
  • id Is the resource locator , and age、name Property

RPC style

Create user (POST)

1
2
3
4
5
6
7
8
9
Request:
POST /user/createUser

{"name": "kirito", "age": 18}

Response:
HTTP 200 OK

{"code": 0, "message": "", "data": {"id": 1, "name": "kirito", "age": 18}}

Query the user (POST)

1
2
3
4
5
6
7
8
9
Request:
POST /user/getUser

{"id": 1}

Response:
HTTP 200 OK

{"code": 0, "message": "", "data": {"id": 1, "name": "kirito", "age": 18}}

Query user list (POST)

1
2
3
4
5
6
7
Request:
POST /user/listUsers

Response:
HTTP 200 OK

{"code": 0, "message": "", "data": {"user": [{"id": 1, "name": "kirito", "age": 18}], "next": "/user/listUsers?offset=1"}}

Modify the user (POST)

1
2
3
4
5
6
7
8
9
Request:
POST /user/modifyUser

{"id": 1, "name": "kirito", "age": 19}

Response:
HTTP 200 OK

{"code": 0, "message": "", "data": {"id": 1, "name": "kirito", "age": 19}}

Change user name (POST)

1
2
3
4
5
6
7
8
9
Request:
POST /user/modifyUserAge

{"id": 1, "age": 20}

Response:
HTTP 200 OK

{"code": 0, "message": "", "data": {"id": 1, "name": "kirito", "age": 20}}

Delete user (DELETE)

1
2
3
4
5
6
7
Request:
POST /user/deleteUser

{"id": 1}

Response:
{"code": 0, "message": ""}

RPC Unlike the style restful One kind of ROA There are some conventions commonly known as norms of style , Each business system is implemented , There are differences , So this is just my personal experience , I hope readers can seek common ground while reserving differences :

  • user For the module name , No need to be like ROA The style is plural
  • Use explicit verb object structures , Rather than CRUD Mapping to HTTP Method,HTTP Method Unified use POST, Query scenarios can also use GET
  • Carried in the return value code、message and data, To map response status and response information , Generally, you can define by yourself code The status code , This article USES the 0 Identification request succeeded ,message Only meaningful if the business response fails ,data Represents the business response result

How to choose RPC and ROA, You need to make decisions according to the business conditions of the product itself . There are the following guidelines :

  • With complex business logic API , You can't use a simple increment 、 Delete 、 Change 、 When looking up the description, you should use RPC style .
  • If the industry standard of the business requires restful style API or ROA Be able to meet business needs , It is advisable to use ROA style .

AWS Mainly adopts RPC style ,Azure、Google Mainly adopts ROA(restful) style , Alibaba cloud OpenAPI Support at the same time RPC and ROA, With RPC Mainly .

Although the norm is innocent , But in ROA Style is in practice , I've seen a lot “ pit ” Of :

  • Ask for resources first , That is, design resources first , Post design interface , High requirements for software development process
  • FALSE ROA Design case 1:tomcat Wait for the application server to process DELETE Methodical HTTP When asked , By default, it is not allowed to carry request body, You need to explicitly open , Result in deletion failure .( This case is a designer's problem , Complex deletion scenarios , Should not be mapped to DELELE, Instead, it should be changed to POST,DELETE Should not carry request body)
  • FALSE ROA Design case 2:restful Parameters carried in the path , May cause regular matching problems , For example, the mailbox is mistakenly used as a path parameter , Or the conflict problem of multi-level path matching ( This case is a designer's problem , Complex query scenarios , Should not be mapped to GET, Instead, it should be changed to POST,path Only resource locators should appear in , Instead of carrying attributes )
  • The response code is 404 when , It's hard to tell if it's true path non-existent , Or does the resource not exist
  • It is not conducive to the scenarios where routing forwarding needs to be configured, such as the docking gateway

What is required by the product I am responsible for Open API The specification needs to meet the following requirements :

  • Back end development design interface , There are clear design ideas , Not because an interface is actually used POST still GET Realization and entanglement , Don't spend too much time on the abstraction of resources ( This does not mean that resources do not need to be designed )
  • When the front end develops the docking interface , Be able to quickly collaborate with the back-end , And it is beneficial to the encapsulation of front-end interface
  • User docking Open API when , The overall style is consistent , Clear module

Sum up , In the choice of design style , I plan to take RPC Design specifications for . To sum up RPC The advantages of style :

  • Meet independent output ,CNStack、 Enterprise Edition 、 Norms of the Ministry of public security
  • API Low design difficulty , It's easy to land
  • Most of Alibaba cloud's mature IAAS Layer product use RPC standard
  • Suitable for complex business scenarios

A detailed RPC Examples of interface documents

Create services

Request parameters

Serial number Field Chinese name Field English name data type Required explain
1 name namestring yes The display name
2 agreement protocolstring yes Enumerated values :http/grpc/webservice
3 Load balancing lbstring yes Enumerated values :random/roundrobin
4 Upstream type upstreamTypestring yes Enumerated values :fixed/discovery
5 The node list nodesarray no upstreamType=fixed Required when , Example :[{“host”: “1.1.1.1”,”port”: “80”,”weight”: “1”}]
6 source idoriginIdstring no
7 The service name serviceNamestring no Name in the registry ,upstreamType=discovery Required when
8 The service description descriptionstring no
9 gateway idgatewayIdstring yes

Returns the parameter

Serial number Field Chinese name Field English name data type explain
1 Response code codeint0 Mark success ;1 Identification failed
2 Response information messagestring
3 In response to the results datastring Back to service id

Request example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
POST /service/createService

Request:
{
"name": "httpbin",
"protocol": "http",
"lb": "random",
"upstreamType": "fixed",
"nodes": [
{
"host": "httpbin.org",
"port": "80",
"weight": "1"
}
],
"gatewayId": "gw-1qw2e3e4"
}

Response:
{
"code": 0,
"message": "",
"serviceId": "s-1qw2e3e4"
}

API Naming specification

  • API Use correctly spelled English , Conform to grammatical norms , Including singular and plural 、 Tenses and language habits

  • There can be no more than one similar meaning but no actual difference in function API, As if there were /user/getUser and /user/describeUser

  • Language habits : Pinyin is prohibited

  • The naming rules for the following common scenarios are fixed

    • The date time type parameter should be named XxxxTime. for example :CreateTime
  • Common operation name specification

    • create: establish
    • modify: change
    • delete: Delete
    • get: Get individual resource details
    • list: Get a list of resources
    • establishRelation: Build resource relationships
    • destroyRelation: Destroy resource relationships

summary

Take a standard recommended in this article as an example :” All interfaces are used POST”, This is not to accommodate low-level architects and front-end and back-end programmers ( What I saw on the community forum ), But to improve development efficiency , Reduce communication costs , Reduce O & M and error location costs , The cost of fooling around , Invested in other, such as business architecture design , Test system , Online monitoring , Disaster recovery and degradation .

The interface specification is not what I summarized , Only RPC and ROA, There are also some remarks that will GraphQL Separate into one category API Design style , For complex query scenarios , Interested students can refer to es Of API file .

Sum up , I plan to adopt RPC Of API Design style .

Reference material

kong:https://docs.konghq.com/gateway/2.8.x/admin-api/

google restful api design:https://cloud.google.com/apis/design?hl=zh-cn

https://www.zhihu.com/question/336797348

原网站

版权声明
本文为[Xujingfeng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230701559326.html