pub struct ApiResponse<T: Serialize> { /* private fields */ }
Expand description
A generic structure representing a standardized API response.
This struct is designed to encapsulate the result of an API call in a consistent format.
It includes fields for the HTTP status code, a human-readable message, and optional data.
The use of generics allows this structure to be flexible and work with any type that implements
the Serialize
trait, making it suitable for JSON serialization (e.g., using serde
).
§Type Parameters
T
: The type of the data field. It must implement theSerialize
trait to ensure compatibility with serialization libraries likeserde
.
§Fields
-
status: u16
Represents the HTTP status code of the response (e.g., 200 for success, 404 for not found). This provides a machine-readable indicator of the response outcome. -
message: String
A human-readable description of the response. This can be used to provide additional context or details about the result (e.g., “Resource created successfully” or “Invalid input”). -
data: Option<T>
Contains the payload of the response, if any. The use ofOption
allows this field to be omitted when there is no data to return (e.g., in case of an error). The typeT
is generic, enabling flexibility for different kinds of data (e.g., user information, list of items, etc.).
§Example
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u32,
name: String,
}
let response = ApiResponse {
status: 0,
message: "User retrieved successfully".to_string(),
data: Some(User {
id: 1,
name: "Alice".to_string(),
}),
};
// Serialize the response to JSON
let json_response = serde_json::to_string(&response).unwrap();
println!("{}", json_response);