当前位置:网站首页>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 !
边栏推荐
- Introduction of network security research direction of Shanghai Jiaotong University
- Anti clockwise rotation method of event arrangement -- PHP implementation
- Serialization oriented - pickle library, JSON Library
- No response after heartbeat startup
- Practical dry goods: deploy mini version message queue based on redis6.0
- Customized version of cacti host template
- priority_ queue
- 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
- Install freeradius3 in the latest version of openwrt
- Btrace tells you how to debug online without restarting the JVM
猜你喜欢
The latest idea activation cracking tutorial, idea permanent activation code, the strongest in history
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 22
Automatic translation between Chinese and English
MPLS experiment
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 12
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 6
Some summaries of the 21st postgraduate entrance examination 823 of network security major of Shanghai Jiaotong University and ideas on how to prepare for the 22nd postgraduate entrance examination pr
nn. Exploration and experiment of batchnorm2d principle
Entitas learning [3] multi context system
MySQL advanced review
随机推荐
8.8.1-PointersOnC-20220214
Detailed explanation of NPM installation and caching mechanism
QQ get group member operation time
Single spa, Qiankun, Friday access practice
Definition and method of string
Reptile learning 3 (winter vacation learning)
2018 meisai modeling summary +latex standard meisai template sharing
AI should take code agriculture? Deepmind offers a programming version of "Alpha dog" alphacode that surpasses nearly half of programmers!
Day01 preliminary packet capture
Map container
Serialization oriented - pickle library, JSON Library
Recommend a cool geospatial data visualization tool with low code
LxC shared directory permission configuration
Iframe to only show a certain part of the page
Snowflake won the 2021 annual database
World document to picture
2021-10-20
Enter the smart Park, and change begins here
Interview question MySQL transaction (TCL) isolation (four characteristics)
French Data Protection Agency: using Google Analytics or violating gdpr