API Response Library
This library provides a consistent structure for API responses, including success and error handling.
Features
- Structured and unified API response format.
- Includes meta for both success and error responses.
- Support segmented error status codes.
- Supports flexible serialization formats like JSON and Protobuf.
- Integration with the Salvo framework for HTTP handling (see examples).
Usage
Run the following Cargo command in your project directory:
Unified API Response Structure
1. Well-defined Structure
Top-Level Fields
Field Name | Type & Example | Required | Meaning | Description |
---|---|---|---|---|
status | "success" or "error" |
Yes | Status of the request | Indicates whether the request was successful. |
data | Any |
Required in success responses | Response data | The data returned when the request is successful. |
error | ApiError object |
Required in error responses | Error information | The error information object returned when the request fails. |
meta | DefaultMeta object |
No | Metadata information | Metadata about the request. |
ApiError
Object Fields
Field Name | Type & Example | Required | Meaning | Description |
---|---|---|---|---|
code | 404 unsigned 32-bit integer |
Yes | Error code | A code that identifies the type of error. |
message | "error message" |
Yes | Error message | Text description of the error. |
details | { "key": "value" } |
No | Error details | The field is of the map<string, string> type and can be used to pass the front-end display configuration, error details and so on. |
DefaultMeta
Object Fields
Meta Field | Type & Example | Required | Meaning | Description |
---|---|---|---|---|
requestId |
"abc4567890" |
No | Request tracking information | Included in the Response Body to maintain consistent data structure in non-standard protocols such as RPC, MQ, etc. |
user |
{ "id": "user-123", "roles": ["admin", "editor"] } |
No | The permission information of the current user, etc. | Notifies the client about the permissions the current user has for this request. |
pagination |
{ "currentPage": 1, "pageSize": 10, "totalPages": 5, "totalRecords": 50, "nextPage": 2, "prevPage": null } |
No | Pagination information | Helps clients with pagination navigation, displaying, and retrieving more data. |
rateLimit |
{ "limit": 1000, "remaining": 990, "restoreRate": 50, "resetAt": "2021-01-01T00:00:00Z" } |
No | Rate limiting information | Includes the limit, remaining calls, restore rate, and reset time, helping clients manage API call frequencies to avoid rate limit issues. |
cost |
{ "actualCost": 10, "requestedQueryCost": 10, "executionTime": "250ms" } |
No | Cost statistics | Provides the cost statistics of the request operation, helping clients understand API resource consumption. |
apiVersion |
"v1.0.1" |
No | Current API version information | Ensures the API version consistency between client and server, beneficial for compatibility management, suitable for internal use or frequently iterated APIs. |
Well-defined JSON Examples
Success Response Example:
Error Response Example:
2. Lightly-defined Structure
Enable the lite
feature to use the lightly-defined structure.
= { = ">=0.13.0", = ["lite"] }
The difference between the lightly-defined structure and the well-defined structure is that the status
field is replaced by the error.code
field, and when the "code" equals 0, it indicates a successful response.
Lightly-defined JSON Examples
Success Response Example:
Error Response Example:
Error Code Specification
The error_code
module provides the ability to construct standardized error-code information.
The standardized error code is segmented and divided according to the decimal literals of unsigned 32-bit integer
.
-
The format is:
{ErrType: 1000-4293} | {ErrPath-Root: 0-99} | {ErrPath-Parent: 0-99} | {ErrPath: 0-99}
So, The value range of the error code is from
1000000000 to 4293999999
inclusive. -
A proposed specification for grouping types of error codes:
Error Type Range Error Type Category Description 1000-1999
Client-Side Error Handles all issues related to user interface interactions, including Web
,Mobile
, andDesktop
clients.2000-2999
Business Service Error Covers issues related to the operation of business layer services. 3000-3999
Infrastructure Service Error Includes database operations, middleware, system observability, network communication, gateway and proxy issues, and other infrastructure service-related errors. 4000-4293
Uncategorized Error Other errors that cannot be classified into specific categories. Suggestion: Except for grouping by the first byte, there is no need to distinguish second-level and third-level parts for error code types (they can just be increased according to the serial numbers), because this is highly likely to lead to the exhaustion of number resources.
-
It is recommended to use the division method of "
product(ErrPath-Root)
|system(ErrPath-Parent)
|module(ErrPath)
" for the error path.
Example
Example of data construction.
use *;
Example of server
use ParseIntError;
use ;
use *;
use ;
/// get user
async
const EP_LV1: ErrPathRoot = X00;
const EP_LV2: ErrPathParent = EP_LV1.Y01;
const EP_LV3: ErrPath = EP_LV2.Z20;
/// get error
async
async
- Get User: http://localhost:7878/
- Get Error: http://localhost:7878/error
- If the
salvo
feature is enabled, api-doc can be accessed: http://localhost:7878/swagger-ui