当前位置:网站首页>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 | Request: |
Query the user (GET)
1 | Request: |
Query user list (GET)
1 | Request: |
establish / Modify the user (PUT)
1 | Request: |
Modify the user (PATCH)
1 | Request: |
Delete user (DELETE)
1 | Request: |
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 | Request: |
Query the user (POST)
1 | Request: |
Query user list (POST)
1 | Request: |
Modify the user (POST)
1 | Request: |
Change user name (POST)
1 | Request: |
Delete user (DELETE)
1 | Request: |
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 | name | string | yes | The display name |
| 2 | agreement | protocol | string | yes | Enumerated values :http/grpc/webservice |
| 3 | Load balancing | lb | string | yes | Enumerated values :random/roundrobin |
| 4 | Upstream type | upstreamType | string | yes | Enumerated values :fixed/discovery |
| 5 | The node list | nodes | array | no | upstreamType=fixed Required when , Example :[{“host”: “1.1.1.1”,”port”: “80”,”weight”: “1”}] |
| 6 | source id | originId | string | no | |
| 7 | The service name | serviceName | string | no | Name in the registry ,upstreamType=discovery Required when |
| 8 | The service description | description | string | no | |
| 9 | gateway id | gatewayId | string | yes |
Returns the parameter
| Serial number | Field Chinese name | Field English name | data type | explain |
|---|---|---|---|---|
| 1 | Response code | code | int | 0 Mark success ;1 Identification failed |
| 2 | Response information | message | string | |
| 3 | In response to the results | data | string | Back to service id |
Request example
1 | POST /service/createService |
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
边栏推荐
- Intelligence Education - how to merge codes when code conflicts occur in multi person collaborative development?
- Yolov5 detecting small targets (with source code)
- . H5 file forgets the database name and uses h5py to print
- Redis setting password
- 1.概率论-组合分析
- CIRIUM(睿思誉)逐渐成为航空公司二氧化碳排放报告的标准
- Principle of skip table
- 【PyQt5系列】修改计数器实现控制
- Wechat multiplayer chat and Roulette Games (websocket Implementation)
- three. Solution to stripe shadow and grid shadow in JS
猜你喜欢

干货来了|《PaaS》合辑抢先看~

Detailed explanation of redis persistence, master-slave and sentry architecture

在线JSON转CSharp(C#)Class工具

MySQL (VIII) - explain

启动appium

浅谈ThreadLocal和InheritableThreadLocal,源码解析

Qt工程报错:-1: error: Cannot run compiler ‘clang++‘. Output:mingw32-make.exe

The original cloud landed in deep water, and the cloud product family of Boyun container released four values

How to tag and label naming before the project release
![[Planet selection] how to efficiently build fine-grained two-way links between roam and thebrain?](/img/ee/ce9f55694b28c391eb07cb11298caf.jpg)
[Planet selection] how to efficiently build fine-grained two-way links between roam and thebrain?
随机推荐
Qt 使用QDomDocument读取xml文件
How MySQL converts a date to a number
Deploy kubersphere in kubernetes
HCIP之路第八次实验
U-Net: Convolutional Networks for Biomedical Image Segmentation
The sandbox has reached a cooperation with football player to bring popular football cartoons and animation into the metauniverse
How do I install MySQL on my computer?
Here comes the dry goods | PAAS collection to see first ~
【唠嗑篇】普通人到底该怎么学技术啊?
279. perfect square
Live broadcast review | how can the container transformation of traditional applications be fast and stable?
Both are hard disk partitions. What is the difference between C disk and D disk?
浅析 Open API 设计规范
职场必备的30套报表模板,满足95%的报表需求,一键套用无需代码
论文写作之WPS安装Mathtype插件编写数学公式
Several characteristics of MySQL database
MySQL (II) - MySQL data type
EXCEL VBA 入门与实用例子
论文伪代码规范,伪代码在线编辑器,
unity 音频可视化方案