18 Essential API Design Rules Every Backend Engineer Should Follow
This article presents a comprehensive checklist of 18 practical API design rules—including signature, encryption, IP whitelisting, rate limiting, validation, unified responses, exception handling, logging, idempotency, pagination, stress testing, async processing, data masking, documentation, request methods, headers, batch operations, and single‑responsibility principles—to help developers build secure, maintainable, and high‑performance services.
1. Signature
To protect API data from tampering, the client concatenates request parameters, a timestamp, and a secret key, then hashes the string (e.g., using MD5) to generate a sign. The server recomputes the sign with the same algorithm and compares the values; matching signs indicate a valid request.
Including a timestamp prevents replay attacks by limiting the request’s validity (commonly 15 minutes).
2. Encryption
Sensitive fields such as passwords, bank cards, or identity numbers must be encrypted before transmission. A typical approach uses AES symmetric encryption on the client side (often with a public key) and decrypts the data on the server before business validation, then re‑encrypts it for storage.
3. IP Whitelist
Restrict API access to a set of trusted IP addresses. Requests from non‑whitelisted IPs are rejected with an “access denied” error. The whitelist can be enforced at the API gateway or web firewall (e.g., ModSecurity).
4. Rate Limiting
Control request volume to avoid overload. Three common strategies are:
Limit total requests per IP per minute (e.g., 10,000).
Limit requests to a specific endpoint per IP per minute (e.g., 2,000).
Limit requests per AK/SK user per minute (e.g., 10,000).
Implementation can use Nginx, Redis, or a dedicated API gateway.
5. Parameter Validation
Validate required fields, data types, lengths, and enum values before business processing. In Java, the Hibernate Validator (annotations such as @NotEmpty, @Size, @Max, @Min) is commonly used, with custom annotations for special cases like dates.
6. Unified Response
Adopt a consistent JSON structure for all responses, e.g.:
{
"code": 0,
"message": null,
"data": [{"id":123,"name":"abc"}]
}Different error scenarios (signature error, no permission, etc.) should return the same top‑level fields with appropriate codes and messages, allowing clients to handle responses uniformly.
7. Unified Exception Handling
All APIs should pass through a gateway that catches runtime exceptions, logs detailed stack traces internally, and returns a generic error payload such as:
{
"code": 500,
"message": "Internal server error",
"data": null
}This prevents leaking sensitive implementation details to third‑party callers.
8. Request Logging
Log request URL, parameters, headers, method, response data, and latency. Include a traceId to correlate logs across services. Logs can be persisted to MongoDB or Elasticsearch and exposed via a UI for partner debugging.
9. Idempotency Design
Ensure that rapid repeated calls with identical parameters do not create duplicate records. Techniques include adding a unique index in the database or storing a requestId in Redis to detect and ignore duplicate submissions.
10. Record Limit
Cap the number of records processed in a single request (commonly 500). Exceeding the limit should return a clear error, and large result sets should be paginated.
11. Stress Testing
Before release, perform load testing (e.g., with JMeter or ApacheBench) to measure QPS and verify that rate‑limiting thresholds are realistic. This helps size the required server pool and avoid unexpected throttling.
12. Asynchronous Processing
For long‑running or batch operations, push a message to a message queue (MQ) and immediately return success. The consumer processes the task asynchronously. Clients can receive results via callback or poll a status endpoint.
13. Data Masking
When returning sensitive data (e.g., phone numbers, bank cards), mask part of the value with asterisks (e.g., 182****887) to reduce exposure risk.
14. Complete API Documentation
Include the following in the docs: endpoint URL, HTTP method, request parameters with descriptions, response schema, error codes, encryption/signature examples, full request demo, and any extra notes such as IP whitelist requirements. Use a consistent naming convention (e.g., camelCase) for fields.
15. Request Method
Prefer GET for parameter‑less queries and POST for requests with a body. POST avoids URL length limits and simplifies parameter expansion, especially when using Feign clients.
16. Request Header
Move common metadata (e.g., traceId, authentication tokens) to HTTP headers rather than query parameters, and extract them via a unified interceptor.
17. Batch Operations
Design endpoints to accept multiple IDs or records in a single call (e.g., /web/v1/order/createBatch) to reduce the number of API calls and improve efficiency.
18. Single Responsibility
Keep each API focused on a single concern. Separate controllers for different client types (web vs. mobile) and for different actions (create vs. fastCreate) to improve clarity and maintainability.
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.
Architect
Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.
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.
