» Rust: Build a REST API with Rocket » 2. Development » 2.3 Data Models

Data Models

Data models represent the structure of the data that the API deals with. These models define the shape of the data entities exchanged between the client and the server.

For example, in this books management api project, a Book model can be defined:

Add dependencies in 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"

Create 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,
}
PrevNext