This page looks best with JavaScript enabled

My Restful API Specification

 ·  ☕ 2 min read

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 /api prefix.
  • 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-tasks rather 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 code to indicate the business status code.
  • Use message to indicate the business status message.
  • Use data to indicate the business data.
    • total is the total number of records.
    • page is the current page number.
    • page_size is the number of records per page.
    • list is the list of records.

6. Endpoint

  • Use nouns rather than verbs, for example /v1/send-mail-tasks or /v1/mails instead of /v1/send-mails

  • Do 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.

1
2
3
4
5
POST /accounts/1/transfers
{
  "to_account_id": 2,
  "amount": 500
}

7. References


WeChat Official Account
WRITTEN BY
WeChat Official Account