Axum Integration
Zyvor’s generated types derive Serialize / Deserialize, so they work with
Axum’s Json extractor directly. No glue code, no wrapper types.
Dependencies
[dependencies]
zyvor = "0.1"
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "chrono"] }
Two pinning rules:
sqlxmust be 0.8 — matching Zyvor. See Installation.- Axum 0.8 uses
{id}path syntax, not:id. If you’re copying an older tutorial,.route("/users/:id", ...)will not match in 0.8.
Including generated code
#![allow(unused)]
fn main() {
#[path = "../.zyvor/generated/mod.rs"]
mod generated;
use generated::{User, UserCreate, UserModel, UserUpdate};
use zyvor::Entity;
}
State
#![allow(unused)]
fn main() {
#[derive(Clone)]
struct AppState { db: PgPool }
}
PgPool is already Clone, and Zyvor’s types are Send + Sync, so this
composes with Axum without friction.
Why you want DTOs (not optional)
Returning PostModel straight from a handler gives you this:
{ "id": 1, "title": "Zyvor Guide", "user_id": 1, "comments": [], "tags": [] }
Notice what’s missing: user. Even if you called .with(Post::user) and
the data is sitting in memory, Zyvor marks back-references #[serde(skip)] to
prevent infinite recursion (Post → User → Posts → Post → …).
So a loaded many-to-one relation is invisible in raw model JSON. A DTO fixes that and gives you a stable API contract:
#![allow(unused)]
fn main() {
#[derive(Serialize)]
struct PostWithUserResponse {
#[serde(flatten)]
post: PostResponse,
user: Option<UserResponse>,
}
}
#[serde(flatten)] keeps the JSON flat — clients see one object, not a nested
{ post: {...}, user: {...} } envelope.
One handler per relation shape
#![allow(unused)]
fn main() {
// 1:N
let users = User::find().with(User::posts).all(&state.db).await?;
// N:1 — Option<Arc<_>>, use as_deref()
let posts = Post::find().with(Post::user).all(&state.db).await?;
let dto = PostWithUserResponse {
post: PostResponse::from(post),
user: post.user.as_deref().map(UserResponse::from),
};
// 1:1 — same shape as N:1
let users = User::find().with(User::profile).all(&state.db).await?;
// M:M — Vec<Arc<_>>, use as_ref()
let tags = Tag::find().with(Tag::posts).all(&state.db).await?;
let posts: Vec<PostResponse> = tag.posts.iter().map(|p| PostResponse::from(p.as_ref())).collect();
// 2-level nested
let users = User::find()
.with_nested(User::posts, |q| q.with(Post::comments))
.all(&state.db).await?;
}
Partial updates over HTTP
Serde fills absent Option fields with None, so clients send only what
they want to change:
#![allow(unused)]
fn main() {
async fn update_user(
State(state): State<AppState>,
Path(id): Path<i32>,
Json(input): Json<UserUpdate>,
) -> Result<Json<UserModel>, StatusCode> {
let user = User::update(&state.db, id, input)
.await
.map_err(|e| db_err(e, "update_user"))?;
Ok(Json(user))
}
}
PUT /users/2
{ "name": "Fakhir Updated", "bio": "Senior Rust Developer" }
Verified: email, age, created_at untouched.
Idempotent seeding
Tag::create fails with 409 on a second run because name is @unique.
Look it up first:
#![allow(unused)]
fn main() {
async fn find_or_create_tag(db: &PgPool, name: &str) -> Result<TagModel, StatusCode> {
if let Some(tag) = Tag::find()
.where_(Tag::name.eq(name))
.all(db).await
.map_err(|e| db_err(e, "find_tag"))?
.into_iter().next()
{
return Ok(tag);
}
Tag::create(db, TagCreate { name: name.to_string() })
.await
.map_err(|e| db_err(e, "create_tag"))
}
}
For the pivot table, raw SQL is the honest tool — Zyvor doesn’t generate pivot insert helpers yet:
#![allow(unused)]
fn main() {
sqlx::query(
"INSERT INTO post_tags (post_id, tag_id) VALUES ($1,$2),($3,$4) \
ON CONFLICT DO NOTHING"
)
.bind(post1.id).bind(tag1.id)
.bind(post1.id).bind(tag2.id)
.execute(&state.db).await?;
}
This is the escape hatch working as intended: the ORM handles the common path, SQL handles the rest.
Verified endpoints
| Endpoint | Shape | Status |
|---|---|---|
GET /users | plain CRUD | ✅ |
POST /users | create | ✅ 201 |
GET /users/{id} | read one | ✅ |
PUT /users/{id} | partial update | ✅ |
DELETE /users/{id} | delete | ✅ 204 |
GET /users/with-posts | 1:N | ✅ |
GET /users/with-profile | 1:1 | ✅ |
GET /posts/with-user | N:1 | ✅ |
GET /tags/with-posts | M:M | ✅ |
GET /users/with-nested | 2-level nested | ✅ |
GET /users/99999 | not found | ✅ 404 |
POST /users duplicate email | unique violation | ✅ 409 |
Full source: zyvor-axum-demo