Designing Elegant API Controllers: Security, Idempotency, and Best Practices
This guide walks through building robust API controller interfaces by covering request signing, RSA encryption, IP whitelisting, rate limiting, parameter validation, unified response formats, exception handling, logging, idempotent design, request size limits, stress testing, asynchronous processing, data masking, and comprehensive documentation.
1. Signature
To prevent tampering, the client concatenates request parameters, a timestamp, and a secret key, then applies an MD5 (or similar) hash to produce a sign value, which is sent either as a query parameter or in the request header.
The API gateway recomputes the signature using the same inputs; if the two signatures match, the request is considered valid and forwarded, otherwise a signature‑error response is returned.
The timestamp limits the signature’s validity (e.g., 15 minutes) to mitigate replay attacks.
2. Encryption
For sensitive fields such as passwords, bank numbers, or identity numbers, the payload should be encrypted before transmission. RSA is commonly used: the client encrypts the data with a public key that is embedded in the front‑end code, while the server holds the corresponding private key to decrypt.
Because the public key can be exposed without risk, only the private key stored securely on the back end protects the data.
3. IP Whitelist
To further protect the API, only IP addresses listed in an allow‑list are permitted to call the endpoint. Requests from non‑whitelisted IPs receive an “access denied” response. The whitelist can be enforced at the gateway or via a web‑application firewall such as ModSecurity.
4. Rate Limiting
Uncontrolled third‑party traffic can overwhelm the service. Three common limiting strategies are:
Limit total requests per IP (e.g., 10 000 calls per minute).
Limit calls to a specific API per IP (e.g., 2 000 calls per minute).
Limit calls per AK/SK user (e.g., 10 000 calls per minute across all APIs).
Implementation can rely on nginx, redis, or an API gateway.
5. Parameter Validation
Validate required fields, types, lengths, and enum values before business logic executes. In Java, the Hibernate Validator framework provides annotations such as @NotEmpty, @Size, @Max, and @Min. Custom annotations handle date or enum checks.
6. Unified Return Values
Standardize JSON responses. Example of a successful response:
{
"code": 0,
"message": null,
"data": [{"id":123,"name":"abc"}]
}Signature error response:
{
"code": 1001,
"message": "签名错误",
"data": null
}No‑permission response:
{
"rt": 10,
"errorMgt": "没有权限",
"result": null
}Using a single structure simplifies integration for third parties.
7. Unified Exception Handling
Catch all exceptions at the gateway, log detailed stack traces internally, and return a generic error JSON such as:
{
"code": 500,
"message": "服务器内部错误",
"data": null
}This prevents leaking internal details while still informing the caller of a failure.
8. Request Logging
Record URL, parameters, headers, HTTP method, response payload, response time, and a traceId for each request. Logs can be persisted to MongoDB or Elasticsearch and exposed via a UI for authorized third‑party users.
9. Idempotent Design
When a third party may retry a request within a short window, ensure the operation is idempotent: the first request creates data, subsequent identical requests return success without creating duplicates. This can be achieved by adding a unique index in the database or storing a requestId in Redis to detect repeats.
10. Record‑Count Limiting
Batch endpoints should cap the number of records per request (commonly 500). Exceeding the limit triggers an explicit error message. The limit should be configurable and agreed upon with the partner to avoid runtime issues.
11. Stress Testing
Before release, perform load testing (e.g., with jmeter or apache bench) to determine QPS capacity and verify that configured rate limits are realistic. This helps size server clusters and avoid unexpected throttling.
12. Asynchronous Processing
For long‑running or batch operations, the API can immediately return success after publishing a message to a message queue ( mq). A consumer processes the message later. The caller can receive the result via a callback or by polling a status endpoint.
13. Data Masking
When returning sensitive fields (e.g., phone numbers, bank cards), mask part of the value with asterisks, such as 182****887, to reduce leakage risk.
14. Complete API Documentation
A thorough document should include:
Endpoint URL
HTTP method (GET/POST)
Request parameters and field descriptions
Response fields and structure
Return codes and error messages
Encryption or signature examples
Full request demo
Additional notes (e.g., IP whitelist)
Adopt a consistent naming convention (e.g., camelCase) and version the API (e.g., v1/query/getCategory) to ease future upgrades.
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.
Programmer XiaoFu
xiaofucode.com – a programmer learning guide driven by the pursuit of profit
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.
