数据模型
数据模型表示 API 处理的数据的结构。 这些模型定义了客户端和服务器之间交换的数据实体的形式。
例如,在这个图书管理 API 项目中,可以定义一个 Book
模型:
添加依赖,Cargo.toml:
@@ -6,4 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+chrono = { version = "0.4.35", features = ["serde"] }
rocket = "0.5.0"
+serde = { version = "1.0.197", features = ["derive"] }
+serde_json = "1.0.114"
创建 src/model.rs:
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Book {
pub id: u32,
pub title: String,
pub author: String,
pub published_at: String,
pub description: String,
pub isbn: String,
pub total_pages: u32,
pub created_at: String,
pub updated_at: String,
}