API Resources
10/30/24Less than 1 minute
API Resources
API Resources (DTOs - Data Transfer Objects) are used to define the shape of data exchanged between the API and clients. They separate internal database models from external API contracts.
DTO Pattern
// API Response DTO
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UserResponse {
pub id: String, // Serialized as string for JS precision
pub username: String,
pub dept_name: Option<String>,
pub created_at: String,
}
// API Request DTO
#[derive(Debug, Deserialize, Validate)]
pub struct CreateUserRequest {
#[validate(length(min = 2, max = 50))]
pub username: String,
#[validate(email)]
pub email: String,
#[validate(length(min = 6))]
pub password: String,
}
// Conversion from Model to DTO
impl From<entity::sys_user::Model> for UserResponse {
fn from(model: entity::sys_user::Model) -> Self {
Self {
id: model.id.to_string(), // Convert i64 to string
username: model.username,
dept_name: None,
created_at: model.created_at.format("%Y-%m-%d %H:%M:%S").to_string(),
}
}
}Best Practices
- Avoid exposing database models directly in API responses
- Use DTOs to control the shape and format of API data
- Handle i64→String conversion for JavaScript compatibility
- Use validation annotations on request DTOs