当前位置:网站首页>22 API design practices
22 API design practices
2022-07-04 12:18:00 【gqltt】
source :22 strip API Design best practices
source :dockone.io/article/2434604
original text :https://betterprogramming.pub/22-best-practices-to-take-your-api-design-skills-to-the-next-level-65569b200b9
Once because of a bad API And feel depressed ?
In this world of microservices , Back end API Consistent design is essential .
today , We will discuss some best practices to follow . We will keep it short and sweet —— So fasten your seat belt , Let's go !
First introduce some terms
whatever API The design follows a pattern called “ Resource oriented design ” Principles :
resources : Resources are part of the data , for example : user
aggregate : A set of resources is called a collection , for example : User list
URL: Identify the location of a resource or collection , for example :/user
1. Yes URL Use kebab-case( Dash small separated form )
for example , If you want to get a list of orders .
Should not be :
/systemOrders or /system_ordersshould :
/system-orders2. Parameters use camelCase( Hump form )
for example , If you want to buy products from a specific store .
Should not be :
/system-orders/{order_id}
perhaps
/system-orders/{OrderId}should :
/system-orders/{orderId}3. A plural name that points to a collection
If you want to get all the users of the system .
Should not be :
GET /user
or :
GET /Usershould :
GET /users4. URL Start with collection , End with identifier
If you want to maintain the unity and consistency of the concept .
Should not be :
GET /shops/:shopId/category/:categoryId/priceThis is very bad , Because it points to an attribute, not a resource .
should :
GET /shops/:shopId/
or
GET /category/:categoryId5. Keep verbs away from your resources URL
Not in URL Use verbs to express your intention . contrary , Use appropriate HTTP Method to describe the operation .
Should not be :
POST /updateuser/{userId}
or :
GET /getusersshould :
PUT /user/{userId}6. For non resources URL Use verbs
If you have an endpoint , It only returns one operation . under these circumstances , You can use verbs . for example , If you want to resend alerts to users .
should :
POST /alarm/245743/resendplease remember , These are not ours CRUD operation . contrary , They are considered to be functions that perform specific work in our system .
7. JSON Attributes use camelCase Hump form
If you are building a request body or response body that is JSON The system of , Then the attribute name should use hump case .
Should not be :
{
user_name: "Mohammad Faisal"
user_id: "1"
}should :
{
userName: "Mohammad Faisal"
userId: "1"
}8. monitor
RESTful HTTP The service must implement /health and /version and /metricsAPI Endpoint . They will provide the following information .
/healthuse 200 OK The status code responds to /health Request .
/versionRespond to with version number /version Request .
/metricsThis endpoint will provide various metrics , Such as average response time .
It is also highly recommended to use /debug and /status Endpoint .
9. Do not use table_name As a resource name
Don't just use the table name as the resource name . In the long run , This laziness is harmful .
Should not be :
product_ordershould :
product-ordersThis is because exposing the underlying architecture is not your goal .
10. Use API Design tools
There are many good API Design tools are used to write good documents , for example :
API The blueprint :https://apiblueprint.org/
Swagger:https://swagger.io/

Have good and detailed documentation for API Users bring good user experience .
11. Use simple ordinal numbers as versions
Always right API Use version control , And move it to the left , Maximize its scope . The version number should be v1,v2 wait .
should :
http://api.domain.com/v1/shops/3/productsAlways in API Using version control in , Because if API Used by external entities , Changing endpoints can break their functionality .
12. Include the total number of resources in your response body
If API Returns a list of objects , The response always contains the total number of resources . You can use total attribute .
Should not be :
{
users: [
...
]
}should :
{
users: [
...
],
total: 34
}13. Accept limit and offset Parameters
stay GET Always accept... In operation limit and offset Parameters .
should :
GET /shops?offset=5&limit=5This is because it is necessary for front-end paging .
14. Get field query parameters
The amount of data returned should also be taken into account . Add one fields Parameters , Public only API Required fields in .
Example : Return only the name of the store , Address and contact information .
GET /shops?fields=id,name,address,contactIn some cases , It also helps to reduce the response size .
15. Not in URL Pass the authentication token in
This is a very bad way , because url Often recorded , The authentication token is also recorded unnecessarily .
Should not be :
GET /shops/123?token=some_kind_of_authenticaiton_tokencontrary , Pass them through the head :
Authorization: Bearer xxxxxx, Extra yyyyyBesides , The authorization token should be short-lived .
16. Verify the content type
The server should not assume the content type . for example , If you accept application/x-www-form-urlencoded, Then an attacker can create a form and trigger a simple POST request .
therefore , Always verify content type , If you want to use the default content type , Please use :
content-type: application/json17. Yes CRUD Function USES HTTP Method
HTTP Method is used to explain CRUD function .
GET: Retrieve the representation of the resource .
POST: Create new resources and sub resources .
PUT: Update existing resources .
PATCH: Update existing resources , It only updates the fields provided , Without updating other fields .
DELETE: Delete existing resources .
18. In the of nested resources URL Use relationships in
Here are some practical examples :
GET /shops/2/products: from shop 2 Get a list of all products .
GET /shops/2/products/31: Get product 31 Details of , product 31 Belong to shop 2.
DELETE /shops/2/products/31: Products should be deleted 31, It belongs to the store 2.
PUT /shops/2/products/31: Products should be updated 31 Information about , Only in resource-URL Upper use PUT, It's not a collection .
POST /shops: A new store should be created , And return the details of the new store created . In collection url Upper use POST.
19. CORS( Cross source resource sharing )
It must be for all public oriented API Support CORS( Cross source resource sharing ) Head .
Consider support CORS Allow the “*” source , And through effective OAuth Token forced authorization .
Avoid combining user credentials with original authentication .
20. Security
At all endpoints 、 Implement on resources and services HTTPS(tls encryption ).
Force and require all callbacks url、 Push notification endpoint and webhooks Use HTTPS.
21. error
When the client sends an invalid or incorrect request to the service , Or pass invalid or incorrect data to the service , When the service rejects the request , There will be errors , Or more specifically , A service error occurred .
Examples include invalid authentication credentials 、 Incorrect parameters 、 Unknown version id etc. .
When a client request is rejected due to one or more service errors , Be sure to return to 4xx HTTP Error code .
Consider handling all attributes , Then multiple verification questions are returned in a single response .
22. The golden rule
If you are right about API The format decision is in doubt , These golden rules can help us make the right decisions .
Flat is better than nested .
Simplicity is better than complexity .
Strings are better than numbers .
Consistency is better than customization .
this is it —— If you've come this far , congratulations ! I hope you learned something .
Hope you have a good day !
边栏推荐
- How do std:: function and function pointer assign values to each other
- How to disable debug messages on sockjs stomp - how to disable debug messages on sockjs Stomp
- QQ one click cookie acquisition
- Reptile learning 4 winter vacation series (3)
- QQ get group link, QR code
- Configure SSH certificate login
- [ES6] template string: `string`, a new symbol in es2015
- Xiaobing · beauty appraisal
- Data communication and network: ch13 Ethernet
- MySQL performance optimization index
猜你喜欢

The latest idea activation cracking tutorial, idea permanent activation code, the strongest in history

Experiment 7. IPv6

Foreach (system.out:: println) usage

Detailed explanation of NPM installation and caching mechanism
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 19](/img/7c/f728e88ca36524f92c56213370399b.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 19

The frost peel off the purple dragon scale, and the xiariba people will talk about database SQL optimization and the principle of indexing (primary / secondary / clustered / non clustered)

Method of setting default items in C # ComboBox control code

Clion configuration of opencv

How to create a new virtual machine

Process communication and thread explanation
随机推荐
The detailed installation process of Ninja security penetration system (Ninjitsu OS V3). Both old and new VM versions can be installed through personal testing, with download sources
VBA, JSON interpretation, table structure -json string conversion
Recommend a cool geospatial data visualization tool with low code
How do std:: function and function pointer assign values to each other
MySQL advanced review
Force buckle 142 Circular linked list II
priority_ queue
DDS-YYDS
Application of slice
2021 annual summary - it seems that I have done everything except studying hard
2021-10-20
Exness: positive I win, negative you lose
Global function Encyclopedia
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23
Reptile learning 3 (winter vacation learning)
In 2022, financial products are not guaranteed?
Data transmission in the network
Reptile learning 4 winter vacation learning series (1)
Configure SSH key to realize login free
DVC use case (VI): Data Registry