Designing API Return Codes and Messages: Best Practices for Backend Services
This article explains how to design clear, consistent API return codes and messages by referencing HTTP status codes, defining code‑message pairs, supporting personalized messages for different clients, and using unified handling for monitoring and alerting, ultimately improving communication and maintenance costs.
In modern client‑server interactions, APIs often rely on return codes to indicate success or failure, but inconsistent definitions (int vs. string, 0 vs. 1, "true" vs. "false") cause confusion and increase maintenance overhead.
1. Introduction
Proper design of API return codes reduces communication friction and eases program maintenance.
2. HTTP Status Code Reference
HTTP status codes are divided into ranges (2XX for success, 5XX for server errors, etc.), providing a clear model for categorizing responses.
Typical backend codes include:
2XX – e.g., 200 → Request succeeded
5XX – e.g., 502 → Server error or code execution failure
3. Parameter Convention
Beyond a numeric code , a human‑readable message is required so developers can understand the result.
Inspired by HTTP status segmentation, error codes can be grouped to simplify identification.
4. Personalized Message
While messages are primarily for engineers, different scenarios may require user‑friendly texts. For example, codes 20001 and 20002 both indicate order‑creation failures but with distinct technical reasons; the user should see a generic apology message, whereas the API returns the precise code and message.
These messages can be stored in a database and cached in Redis or the API server for fast lookup.
During response generation, the system matches application_id+code to replace the generic message with the appropriate localized text, allowing mobile apps, mini‑programs, and web clients to see different messages.
5. Unified Handling of Return Information
With a standardized code , Nginx or APM tools can aggregate request counts per code, enabling statistical dashboards and alerting (e.g., trigger an alarm when the count of code 99999 exceeds a threshold).
Visualizing code distribution helps identify system or business‑process issues.
Conclusion
A well‑designed return‑code scheme improves communication efficiency, reduces code maintenance cost, and facilitates monitoring and alerting across backend services.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.