Mainly for standardizing the APIs I write myself, and also to help LLMs understand my APIs better.
1. Domain
- Use a dedicated domain whenever possible, for example
api.example.com.
2. Path
- Always use lowercase letters.
- Do not include an
/apiprefix. - Do not include file extensions.
- Do not put
/at the end. For a Restful API,/separates resource levels, and a trailing/causes confusion. - Use a versioned path
/v1. - Use plural forms, for example
/v1/users. - Use
-instead of_for readability, so/v1/mail-tasksrather than/v1/mail_tasks.
3. Query
- Name fields in lowercase snake case, for example
?first_name=abc. - The total length of a query should stay within 2000 characters.
- The POST method must not use query parameters.
- Separate array parameters with commas, for example
?ids=1,2,3.
4. Method
Many teams in China use only the GET and POST methods for various reasons, or even only POST. Here I only describe the purpose of each method according to its semantics.
- GET: Retrieve a resource, idempotent. Note that the GET method should not modify a resource; the main concern is caching.
- POST: Create a resource, not idempotent.
- PUT: Update a resource, providing the complete set of attributes, idempotent.
- PATCH: Update a resource, providing a partial set of attributes, not idempotent.
- DELETE: Delete a resource, idempotent.
- HEAD: Retrieve metadata about a resource, idempotent.
- OPTIONS: Retrieve information about which attributes of a resource the client is allowed to change, idempotent.
5. Response
- Use the JSON format.
- Use HTTP status codes to indicate the request status.
- Use
codeto indicate the business status code. - Use
messageto indicate the business status message. - Use
datato indicate the business data.totalis the total number of records.pageis the current page number.page_sizeis the number of records per page.listis the list of records.
6. Endpoint
Use nouns rather than verbs, for example
/v1/send-mail-tasksor/v1/mailsinstead of/v1/send-mailsDo not include verbs in resources. Here is a counterexample:
POST /accounts/1/transfer/500/to/2.
Resources should be represented by nouns, and actions should be represented by HTTP methods.
| |
