Click for PDF manual V2.0 – > interview | springboot | springcloud | programming ideas

  1. Use kebab-case (lowercase delimited with dash) for urls
  2. Parameters using camelCase (hump form)
  3. The complex name pointing to the collection
  4. A URL starts with a collection and ends with an identifier
  5. Keep verbs out of your resource URLS
  6. Use verbs for non-resource urls
  7. JSON attributes use camelCase camel form
  8. monitoring
  9. Do not use table_name as the resource name
  10. Use API design tools
  11. Use simple Ordinal Numbers as versions
  12. Include the total resource number in your response body
  13. Accept limit and offset arguments
  14. Gets the field query parameters
  15. Do not pass authentication tokens in urls
  16. Validate content types
  17. Use HTTP methods for CRUD functions
  18. Use relationships in urls for nested resources
  19. CORS (Cross-source resource sharing)
  20. security
  21. error
  22. The golden rule

Ever been frustrated by a bad API?

In this microservice world, a consistent design of back-end apis is essential.

Today, we’ll discuss some best practices to follow. We’re going to keep it short and sweet — so buckle up and go!

Let’s start with some terminology

Any API design follows a principle called resource-oriented design:

  • Resource: A resource is a part of data, such as a user
  • Collection: A group of resources called a collection, for example, a list of users
  • URL: Identifies the location of a resource or collection, for example, /user

1. Use kebab-case for urls (lowercase delimited with dash line)

For example, if you want to get a list of orders.

Should not:

/ systemOrders or/system_ordersCopy the code

Should be:

/system-orders  
Copy the code

2. Parameter use camelCase (hump form)

For example, if you want to buy products from a particular store.

Should not:

/system-orders/{order_id}  
Copy the code

Or:

/system-orders/{OrderId}  
Copy the code

Should be:

/system-orders/{orderId}  
Copy the code

3. The plural name pointing to the collection

If you want to get all the users of the system.

Should not:

GET /user  
Copy the code

Or:

GET /User  
Copy the code

Should be:

GET /users  
Copy the code

4. A URL starts with a collection and ends with an identifier

If you want to keep the concept simple and consistent.

Should not:

GET /shops/:shopId/category/:categoryId/price  
Copy the code

This is bad because it points to an attribute rather than a resource.

Should be:

GET /shops/:shopId/ or GET /category/:categoryIdCopy the code

5. Keep verbs out of your resource urls

Do not use verbs in urls to express your intent. Instead, use appropriate HTTP methods to describe operations.

Should not:

POST /updateuser/{userId}  
Copy the code

Or:

GET /getusers  
Copy the code

Should be:

PUT /user/{userId}  
Copy the code

6. Use verbs for non-resource urls

If you have an endpoint, it only returns one operation. In this case, you can use a verb. For example, if you want to resend an alert to the user.

Should be:

POST /alarm/245743/resend  
Copy the code

Keep in mind that these are not our CRUD operations. Rather, they are thought of as functions that perform a particular job in our system.

7. Use camelCase camel form for JSON attributes

If you are building a system with a JSON request or response body, the property names should be in camel case.

Should not:

{  
   user_name: "Mohammad Faisal"  
   user_id: "1"  
}  
Copy the code

Should be:

{  
   userName: "Mohammad Faisal"  
   userId: "1"  
}  
Copy the code

Monitoring 8.

RESTful HTTP services must implement /health and /version and /metricsAPI endpoints. They will provide the following information.

/health

Respond to the request to /health with a 200 OK status code.

/version

Respond to requests for /version with the version number.

/metrics

This endpoint will provide various metrics, such as average response time.

The use of /debug and /status endpoints is also highly recommended.

9. Do not use table_name as the resource name

Do not use only table names as resource names. In the long run, this laziness is harmful.

Should not:

product_order  
Copy the code

Should be:

product-orders  
Copy the code

This is because exposing the underlying architecture is not your goal.

10. Use API design tools

There are many good API design tools for writing good documentation, such as:

  • API Blueprint: APIBlueprint.org/
  • Swagger: Swagger. IO /

Having good and detailed documentation makes for a good user experience for API users.

11. Use simple Ordinal Numbers as versions

Always use version control on the API and move it to the left to give it maximum scope. The version numbers should be V1, v2 and so on.

Should be: http://api.domain.com/v1/shops/3/products

Always use versioning in the API, because changing endpoints may break their functionality if the API is used by external entities.

12. Include the total resource count in your response body

If the API returns a list of objects, the response always contains the total number of resources. You can use the total attribute for this.

Should not:

{  
  users: [   
     ...  
  ]  
}  
Copy the code

Should be:

{ users: [ ... ] , total: 34 }Copy the code

13. Accept the limit and offset parameters

Always accept limit and offset arguments in a GET operation.

Should be:

GET /shops? offset=5&limit=5Copy the code

This is because it is necessary for front end paging.

14. Obtain the field query parameters

The amount of data returned should also be taken into account. Add a fields parameter that exposes only the required fields in the API.

Example:

Return only the name, address, and contact information of the store.

GET /shops? fields=id,name,address,contactCopy the code

In some cases, it also helps reduce the response size.

15. Do not pass authentication tokens in urls

This is a very bad practice, because urls are often logged, and authentication tokens are logged unnecessarily.

Should not:

GET /shops/123? token=some_kind_of_authenticaiton_tokenCopy the code

Instead, pass them through the head:

Authorization: Bearer xxxxxx, Extra yyyyy  
Copy the code

In addition, authorization tokens should be short-lived.

16. Verify the content type

The server should not assume content types. 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 validate the content type. If you want to use the default content type, use:

content-type: application/json  
Copy the code

17. Use HTTP methods for CRUD functions

HTTP methods are used to explain CRUD functionality.

GET: Retrieves the representation of the resource.

POST: Creates new resources and sub-resources.

PUT: Updates existing resources.

PATCH: Updates an existing resource. It updates only the fields provided, not the other fields.

DELETE: deletes an existing resource.

18. Use relationships in urls for nested resources

Here are some examples in action:

  • GET /shops/2/products: Get a list of all products from Shop 2.
  • GET /shops/2/products/31: Gets the details of product 31, which belongs to Shop 2.
  • DELETE /shops/2/products/31: Should delete product 31, which belongs to store 2.
  • PUT /shops/2/products/31: Product 31 should be updated to use PUT only on resource-urls, not collections.
  • POST /shops: Should create a new store and return the details of the new store created. Use POST on the collection URL.

19. CORS (Cross-source resource Sharing)

Be sure to support CORS (Cross-source resource sharing) headers for all public-facing apis.

Consider supporting “*” sources permitted by CORS and enforcing authorization with a valid OAuth token.

Avoid combining user credentials with original authentication.

Safety 20.

Enforce HTTPS (TLS encryption) on all endpoints, resources, and services.

Force and require HTTPS for all callback urls, push notification endpoints, and Webhooks.

21. The error

An error occurs, or more specifically, a service error occurs, when a client makes an invalid or incorrect request to the service, or passes invalid or incorrect data to the service, and the service rejects the request.

Examples include invalid authentication credentials, incorrect parameters, unknown version ids, and so on.

  • Be sure to return a 4xx HTTP error code when a client request is rejected due to one or more service errors.
  • Consider processing all the attributes and then returning multiple validation questions in a single response.

22. The Golden Rule

If you have questions about an API format decision, these golden rules can help us make the right decision.

  • Flat is better than nesting.
  • Simple is better than complex.
  • Strings are better than numbers.
  • Consistency is better than customization.

That’s it — if you’ve made it this far, congratulations! I hope you learned something.

Hope you have a great day!

Translator: Mr. LZC, software engineer, DevOpsDays, HDZ Shenzhen core organizer, currently working for Huawei, engaged in cloud computing, focusing on K8s and micro services.

Original text: betterprogramming pub / 22 – best – pra…


Recommend 3 original Springboot +Vue projects, with complete video explanation and documentation and source code:

Build a complete project from Springboot+ ElasticSearch + Canal

  • Video tutorial: www.bilibili.com/video/BV1Jq…
  • A complete development documents: www.zhuawaba.com/post/124
  • Online demos: www.zhuawaba.com/dailyhub

【VueAdmin】 hand to hand teach you to develop SpringBoot+Jwt+Vue back-end separation management system

  • Full 800 – minute video tutorial: www.bilibili.com/video/BV1af…
  • Complete development document front end: www.zhuawaba.com/post/18
  • Full development documentation backend: www.zhuawaba.com/post/19
  • Online demos: www.markerhub.com/vueadmin

【VueBlog】 Based on SpringBoot+Vue development of the front and back end separation blog project complete teaching

  • Full 200 – minute video tutorial: www.bilibili.com/video/BV1PQ…
  • Full development documentation: www.zhuawaba.com/post/17
  • Online demos: www.markerhub.com:8084/blogs

If you have any questions, please come to my official account [Java Q&A Society] and ask me