18 Must‑Know API Design Rules for Secure and Scalable Backends
This article presents 18 essential API design rules covering signature verification, encryption, IP whitelisting, rate limiting, parameter validation, unified responses and error handling, logging, idempotency, request size limits, stress testing, asynchronous processing, data masking, comprehensive documentation, proper HTTP methods, header usage, batch operations, and single‑responsibility principles.
Hello everyone, I’m Su San, back again.
Previously I wrote an article "18 Table Design Rules" that was well received. Continuing the design theme, I now summarize 18 API design rules to help you.
1. Signature
To prevent API data tampering, sign requests by concatenating request parameters, a timestamp, and a secret key, then hashing (e.g., MD5) to generate a sign. Include sign in the request (parameter or header). The gateway recomputes the sign and compares; matching signs indicate a valid request, otherwise a signature error is returned.
Timestamp is added for security, limiting request validity (e.g., 15 minutes).
Two secret key approaches: a fixed privateKey shared by both parties, or an AK/SK pair where the server provides AK (accessKey) and SK (secret) – the client sends AK in the header and uses SK for signing.
2. Encryption
Sensitive data (passwords, bank cards, IDs) must not be transmitted in plain text. Use encryption such as AES for symmetric encryption. The frontend encrypts passwords with a public key; the server decrypts, validates, then re‑encrypts before storing.
3. IP Whitelist
Restrict API access to allowed IP addresses. Only IPs on the whitelist can reach the API; others receive an access‑denied response. Whitelisting can be enforced at the gateway or via a web firewall (e.g., ModSecurity).
4. Rate Limiting
Control request frequency to prevent overload. Three common limits: per‑IP total requests, per‑IP per‑endpoint requests, and per‑user (AK/SK) total requests. Implement with Nginx, Redis, or an API gateway.
5. Parameter Validation
Validate required fields, types, lengths, and enum values to reject invalid requests early. In Java, Hibernate Validator (annotations like @NotEmpty, @Size, @Max, @Min) is widely used; custom annotations can handle dates and enums.
6. Unified Response Format
Define a single JSON structure, e.g.:
{
"code": 0,
"message": null,
"data": [{"id":123,"name":"abc"}]
}All error cases (signature error, permission error, etc.) should conform to this format, allowing clients to parse responses consistently.
7. Unified Exception Handling
Catch business exceptions in the gateway, convert them to a standard error response (e.g., code 500, message "Internal Server Error"), and log detailed stack traces internally. This prevents leaking sensitive information to third‑party callers.
{
"code": 500,
"message": "服务器内部错误",
"data": null
}8. Request Logging
Log URL, parameters, headers, method, response data, and latency. Include a traceId to correlate logs. Logs can be stored in MongoDB or Elasticsearch and optionally exposed via a UI for partners.
9. Idempotency
Ensure repeated identical requests within a short window do not create duplicate records. Implement via a unique database index or store a requestId in Redis.
10. Record Limit
Limit batch request size (e.g., max 500 records) to avoid timeouts. Larger batches should be paginated.
11. Stress Testing
Perform load testing (JMeter, Apache Bench) to determine QPS and capacity before release.
12. Asynchronous Processing
For long‑running tasks, send an MQ message and return success immediately. The consumer processes the message; the client can receive results via callback or polling.
13. Data Masking
Mask sensitive fields in responses (e.g., phone numbers as 182****887) to reduce leakage risk.
14. Complete API Documentation
Include endpoint, method, request parameters, response fields, error codes, encryption/signature examples, full request demo, and extra notes (e.g., IP whitelist). Use consistent naming (camelCase), define field types/lengths, and standard time format (yyyy‑MM‑dd HH:mm:ss).
15. HTTP Methods
Use GET for parameter‑less queries and POST for requests with parameters. GET has a length limit (~5000 characters); POST does not.
16. Request Headers
Place common parameters (e.g., traceId) in headers instead of request bodies.
17. Batch Operations
Design APIs to support batch queries, inserts, updates, and deletes to avoid excessive single‑record calls.
18. Single Responsibility
Keep each API focused. Separate web and mobile endpoints and separate normal vs. fast order creation, e.g.:
/web/v1/order
/web/v1/order/fastCreate
/mobile/v1/order
/mobile/v1/order/fastCreateThis reduces maintenance complexity.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
