Response
10/30/24Less than 1 minute
Standardized API Response: ApiResponse<T>
To ensure consistent, predictable API interfaces and smooth frontend-backend collaboration, we implemented a standardized API response structure called ApiResponse<T>.
Golden Rule
All API endpoints in this project should return responses generated by ApiResponse. Handlers should not manually create Json or (StatusCode, ...) tuples.
JSON Response Structure
On Success
{
"message": "Operation successful",
"data": {
"id": 123,
"username": "alice",
"email": "alice@example.com"
}
}On Failure / No Data
{
"message": "User not found",
"data": {}
}Core Struct Definition
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ApiResponse<T> {
pub message: String,
pub data: T,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct EmptyData {}How to Use ApiResponse
1. Success Response (200 OK, 201 Created)
async fn get_user_profile(user_info: UserInfo) -> Response {
let user_data = UserData { id: user_info.uid, ... };
ApiResponse::ok(user_data) // 200 OK
}2. Error Response
// 400 Bad Request
ApiResponse::bad_request("Invalid input")
// 401 Unauthorized
ApiResponse::unauthorized("Token expired")
// 403 Forbidden
ApiResponse::forbidden("Insufficient permissions")
// 404 Not Found
ApiResponse::not_found("User not found")
// 500 Internal Server Error
ApiResponse::internal_server_error("Database error")3. Pattern: Handler Calls Service → ApiResponse
pub async fn list_users() -> Response {
let result = UserService::list().await;
ApiResponse::from_result(result)
}This pattern cleanly separates business logic from response formatting.
Implementation: impl IntoResponse
The "magic" that lets handlers return ApiResponse<T> directly is its implementation of Axum's IntoResponse trait:
impl<T> IntoResponse for ApiResponse<T>
where
T: Serialize,
{
fn into_response(self) -> Response {
// 1. Serialize to JSON
// 2. Handle serialization failure (500 error)
// 3. Set HTTP headers
// 4. Combine into Axum Response
}
}This completely hides the complexity of building HTTP responses.