当前位置:网站首页>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_orders
should :
/system-orders
2. 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 /User
should :
GET /users
4. 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/price
This is very bad , Because it points to an attribute, not a resource .
should :
GET /shops/:shopId/
or
GET /category/:categoryId
5. 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 /getusers
should :
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/resend
please 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 .
/health
use 200 OK The status code responds to /health Request .
/version
Respond to with version number /version Request .
/metrics
This 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_order
should :
product-orders
This 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/products
Always 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=5
This 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,contact
In 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_token
contrary , Pass them through the head :
Authorization: Bearer xxxxxx, Extra yyyyy
Besides , 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/json
17. 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
- Process communication and thread explanation
- Here, the DDS tutorial you want | first experience of fastdds - source code compilation & Installation & Testing
- What if the chat record is gone? How to restore wechat chat records on Apple Mobile
- Leetcode: 408 sliding window median
- 2021-10-20
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 10
- IPv6 experiment
- QQ group collection
- Lvs+kept highly available cluster
猜你喜欢
Properties and methods of OS Library
Source code analysis of the implementation mechanism of multisets in guava class library
Introduction of network security research direction of Shanghai Jiaotong University
Alibaba cloud server connection intranet operation
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 6
Single spa, Qiankun, Friday access practice
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 12
French Data Protection Agency: using Google Analytics or violating gdpr
OSI seven layer reference model
2020 Summary - Magic year, magic me
随机推荐
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 21
Global function Encyclopedia
How to use the mongodb ID array to get multiple documents- How to get multiple document using array of MongoDb id?
Ternsort model integration summary
Review of week 278 of leetcode II
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 22
French Data Protection Agency: using Google Analytics or violating gdpr
Application of slice
Summary of Shanghai Jiaotong University postgraduate entrance examination module -- cryptography
Day01 preliminary packet capture
How to create a new virtual machine
Iframe to only show a certain part of the page
queue
[directory] search
Supercomputing simulation research has determined a safe and effective carbon capture and storage route
. Does net 4 have a built-in JSON serializer / deserializer- Does . NET 4 have a built-in JSON serializer/deserializer?
template<typename MAP, typename LIST, typename First, typename ... Keytypes > recursive call with indefinite parameters - beauty of Pan China
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)
SSH principle and public key authentication
Simple understanding of seesion, cookies, tokens