use validator::Validate;
#[derive(Debug, Deserialize, Validate, ToSchema)]
pub struct CreateUserRequest {
#[validate(email)]
#[schema(example = "user@example.com")]
pub email: String,
#[validate(length(min = 8, max = 64))]
pub password: String,
#[validate(length(min = 1, max = 100))]
#[schema(example = "Jane Doe")]
pub name: String,
}
pub async fn create_user(
State(state): State<AppState>,
Json(req): Json<CreateUserRequest>,
) -> Result<Json<UserResponse>, AppError> {
req.validate()?;
// ...
}
#[utoipa::path(
post,
path = "/users",
tag = "users",
request_body = CreateUserRequest,
responses(
(status = 201, description = "User created", body = UserResponse),
(status = 400, description = "Validation error")
)
)]
pub async fn create_user(/* ... */) { }
#[derive(OpenApi)]
#[openapi(
info(title = "My API", version = "1.0.0"),
tags((name = "users", description = "User management"))
)]
struct ApiDoc;
pub fn create_router(state: AppState) -> Router {
let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi())
.routes(routes!(create_user))
.split_for_parts();
router
.merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", api))
.with_state(state)
}
1---2name: rust-backend-api3description: Provides API design patterns for Rust backends including request validation with validator, OpenAPI documentation with utoipa, and SwaggerUI integration. Use when building REST APIs with Axum, adding request validation, generating OpenAPI specs, or setting up API documentation.4---5
6<objective>
7Enable production-quality REST API development with type-safe request validation, automatic OpenAPI documentation, and interactive API exploration.
8</objective>
9
10<essential_principles>
111. **Validation at the Edge** - Validate all external input immediately.
122. **Code-First OpenAPI** - Documentation lives in the code via derive macros.
133. **Schema as Contract** - ToSchema-derived types define the API contract.
14</essential_principles>
15
16<patterns>
17<pattern name="validation">
18**Request Validation**
19
20```rust
21use validator::Validate;
22
23#[derive(Debug, Deserialize, Validate, ToSchema)]
24pub struct CreateUserRequest {
25 #[validate(email)]
26 #[schema(example = "user@example.com")]
27 pub email: String,
28
29 #[validate(length(min = 8, max = 64))]
30 pub password: String,
31
32 #[validate(length(min = 1, max = 100))]
33 #[schema(example = "Jane Doe")]
34 pub name: String,
35}
36
37pub async fn create_user(
38 State(state): State<AppState>,
39 Json(req): Json<CreateUserRequest>,
40) -> Result<Json<UserResponse>, AppError> {
41 req.validate()?;
42 // ...
43}
44```
45</pattern>
46
47<pattern name="openapi">
48**OpenAPI with utoipa**
49
50```rust
51#[utoipa::path(
52 post,
53 path = "/users",
54 tag = "users",
55 request_body = CreateUserRequest,
56 responses(
57 (status = 201, description = "User created", body = UserResponse),
58 (status = 400, description = "Validation error")
59 )
60)]
61pub async fn create_user(/* ... */) { }
62
63#[derive(OpenApi)]
64#[openapi(
65 info(title = "My API", version = "1.0.0"),
66 tags((name = "users", description = "User management"))
67)]
68struct ApiDoc;
69
70pub fn create_router(state: AppState) -> Router {
71 let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi())
72 .routes(routes!(create_user))
73 .split_for_parts();
74
75 router
76 .merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", api))
77 .with_state(state)
78}
79```
80</pattern>
81</patterns>
82
83<success_criteria>
84- [ ] All request types derive Validate with constraints
85- [ ] Validation errors return 400 with field-specific messages
86- [ ] All endpoints have #[utoipa::path] documentation
87- [ ] SwaggerUI accessible and shows all endpoints
88- [ ] OpenAPI spec includes security schemes if using auth
89</success_criteria>