capy-framework 0.10.0

An opinionated full-stack Rust web framework with strong conventions and sensible defaults.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# Capy

**A calmer way to build web apps in Rust.**

Strong conventions. Sensible defaults. No framework assembly required.

Capy is an opinionated full-stack Rust web framework with strong conventions and
sensible defaults. It combines a Rust backend with a first-class frontend workflow
so you can start building the application instead of assembling the framework.

```toml
[dependencies]
capy = { package = "capy-framework", version = "0.10.0" }
```

Application code normally starts with `use capy::prelude::*;`. Native Axum,
SeaORM, Tokio and Serde APIs remain available through named re-exports.
Generate a complete application with `capy new blog` using `capy-cli`.

Generated resources keep entities separate from serialized DTOs. Use bounded `Page<ResponseDto>` collections and explicit public DTOs; see the executable tutorial below.
Production uses JSON request logs with request ID, method, route, status, and latency.
Set `RUST_LOG` to override the default INFO filter. Responses include `x-request-id`;
internal errors are sanitized. Prefer running the compiled release binary in production.

MIT licensed. See LICENSE. This is an initial developer preview, not a production-readiness claim.

New applications use `App::api_routes(routes)` to mount paths under `/api` and
`App::frontend("frontend/dist")` for static assets and SPA fallback. `App::routes`
continues to register unprefixed routes. Explicit web routes and API handlers take
precedence; API 404s never return the SPA. Missing static assets return 404, while
GET/HEAD browser paths without a file extension fall back to `index.html`.

`capy dev` runs the backend and Vite together; `capy build` produces frontend assets
and a release binary. The production backend requires no Node server. Deploy the
`frontend/dist` directory with the binary and run from the project root with
`APP_ENVIRONMENT=production`; missing frontend builds fail before database startup.
`into_router` constructs only the HTTP service; `run`/`run_command` perform startup
validation. Existing backend-only apps keep their current behavior.

## Optional identity

Capy 0.6.0 introduced experimental cookie sessions through the `auth` feature. Run
`capy make:auth` to install conventional SeaORM migrations, safe DTOs, CSRF-aware
React helpers and an application-owned reset-delivery hook. Use `AuthUser` or
`OptionalAuth` and ordinary `Policy` implementations for protected resources.
Production requires HTTPS and a real reset-delivery adapter; generated local
delivery is development-only. See the [auth API](https://docs.rs/capy-auth/0.10.0/capy_auth/).

## Build a Complete Feature

Run `capy make:auth --frontend` then
`capy make:resource Post title:string slug:string:unique body:text published:boolean=false --frontend`.
Apply `capy db:migrate`, `capy db:seed`, then `capy dev`. The
[primary tutorial](https://github.com/capy-rs/capy/blob/main/docs/complete-feature.md)
connects generated CRUD, auth pages, typed client calls, TestApp/TestSession and fixtures.
The lower-level API tutorial follows below.

<!-- first-app tutorial: synchronized with docs/first-app.md -->

# Your first Posts API

This tutorial targets **Capy 0.10.0**, with Rust 1.88 or later.
Keep the CLI and framework on the same release. For the primary generated full-stack
workflow, start with [Build a Complete Feature](https://github.com/capy-rs/capy/blob/main/docs/complete-feature.md).

It creates a JSON API with SQLite first, then shows PostgreSQL and generated React
contracts. All application imports come from `capy`; no direct Axum, SeaORM, Serde,
Tokio or Schemars dependencies are needed.

## 1. Install and create

Install Rust through [rustup](https://rustup.rs), with a native linker/toolchain for
your OS. Install the matching CLI and create an application:

```sh
rustup component add rustfmt
cargo install capy-cli --version 0.10.0 --locked
capy --version
capy new blog --api
cd blog
```

The generated Cargo.toml uses capy-framework 0.10.0 from crates.io, including its
testing feature in development dependencies. No local source override is needed.

Cargo installs the executable in `$HOME/.cargo/bin`; make sure that directory is
on `PATH` (rustup normally configures it). The first installation/application build
compiles dependencies and takes longer than later runs. A minimal Linux image needs
a C compiler/linker, such as Debian/Ubuntu's `build-essential` package. SQLite is
bundled; no SQLite service or PostgreSQL client library is required.

## 2. Choose a database

The generated SQLite configuration works immediately:

```dotenv
DATABASE_URL=sqlite://database/app.sqlite?mode=rwc
```

You do not need to create a `.env` file for this default. For PostgreSQL, create a
**disposable tutorial database**. One option is Docker:

```sh
docker run --rm -d --name capy-postgres \
  -e POSTGRES_PASSWORD=capy-test -e POSTGRES_DB=capy_blog \
  -p 127.0.0.1:5432:5432 postgres:17-alpine
export DATABASE_URL=postgres://postgres:capy-test@127.0.0.1:5432/capy_blog
```

Wait for `docker exec capy-postgres pg_isready -U postgres -d capy_blog` to report
that connections are accepted. Keep `DATABASE_URL` in the shell used for migration
and serving, or put it in an ignored `.env` file. The same code and migrations below
work on both databases. Use application-specific credentials outside this tutorial.

## 3. Generate the components

```sh
capy make:model Post
capy make:migration create_posts_table
capy make:request CreatePostRequest
capy make:controller PostController
```

These commands register compilable skeletons. Add your domain fields and handlers
by replacing the indicated files with the complete examples below. Keep the
registrations generated in each `mod.rs` file.

## 4. Add the model field

Replace `app/models/post.rs`. The generator already supplies serialization; we add
one `title` column. The `Post` entity and `PostModel` aliases are already registered.

<!-- file: app/models/post.rs -->
```rust
use capy::sea_orm::{self, entity::prelude::*};

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "posts")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i32,
    pub title: String,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}
```

## 5. Define the migration

Replace the generated file ending in `_create_posts_table.rs` under
`database/migrations/`. Keep its generated filename and the migrator registry.
Apply migrations explicitly; starting the server never changes the schema.

<!-- file: database/migrations/*_create_posts_table.rs -->
```rust
use capy::migration::{self as sea_orm_migration, prelude::*};

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(Alias::new("posts"))
                    .col(
                        ColumnDef::new(Alias::new("id"))
                            .integer()
                            .not_null()
                            .auto_increment()
                            .primary_key(),
                    )
                    .col(
                        ColumnDef::new(Alias::new("title"))
                            .string_len(200)
                            .not_null(),
                    )
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(Alias::new("posts")).to_owned())
            .await
    }
}
```

## 6. Validate input

Replace `app/requests/create_post_request.rs`. Both create and update require a title
between 2 and 200 characters. Invalid input receives HTTP 422 before the handler runs.

<!-- file: app/requests/create_post_request.rs -->
```rust
use capy::prelude::*;

#[derive(Debug, Deserialize, Validate, ApiSchema)]
#[serde(crate = "capy::serde")]
#[schemars(crate = "capy::schema")]
#[validate(crate = "capy::validator")]
pub struct CreatePostRequest {
    #[validate(length(min = 2, max = 200))]
    pub title: String,
}
```

## 7. Implement the controller

Replace `app/controllers/post_controller.rs`. `Context` supplies the typed database
connection. Native SeaORM errors convert through `?`; missing rows become JSON 404s.
`Query<Pagination>` defaults to page 1 with 20 items and rejects page sizes outside
1–100. Try `/api/posts?page=2&per_page=20`; lists return `data` plus `meta` with
`page`, `per_page`, `total`, and `last_page`. Empty collections have `last_page: 1`.
The explicit `PostResponse` keeps future private database columns out of the API.

<!-- file: app/controllers/post_controller.rs -->
```rust
use crate::app::{
    models::{post, Post, PostModel},
    requests::create_post_request::CreatePostRequest,
};
use capy::{
    prelude::*,
    sea_orm::{ActiveModelTrait, EntityTrait, IntoActiveModel, PaginatorTrait, QueryOrder, Set},
};

pub struct PostController;

#[derive(Serialize, ApiSchema)]
#[serde(crate = "capy::serde")]
#[schemars(crate = "capy::schema")]
pub struct PostResponse {
    pub id: i32,
    pub title: String,
}

impl From<PostModel> for PostResponse {
    fn from(post: PostModel) -> Self {
        Self {
            id: post.id,
            title: post.title,
        }
    }
}

impl PostController {
    pub async fn index(
        Context(ctx): Context,
        Query(page): Query<Pagination>,
    ) -> Result<Json<Page<PostResponse>>> {
        let query = Post::find()
            .order_by_asc(post::Column::Id)
            .paginate(&ctx.db, page.per_page());
        let total = query.num_items().await?;
        let posts = query.fetch_page(page.page() - 1).await?;
        Ok(Json(Page::new(
            posts.into_iter().map(PostResponse::from).collect(),
            page,
            total,
        )))
    }

    pub async fn store(
        Context(ctx): Context,
        Validated(request): Validated<CreatePostRequest>,
    ) -> Result<Created<PostResponse>> {
        Ok(Created(
            post::ActiveModel {
                title: Set(request.title),
                ..Default::default()
            }
            .insert(&ctx.db)
            .await?
            .into(),
        ))
    }

    pub async fn show(Context(ctx): Context, Path(id): Path<i32>) -> Result<Json<PostResponse>> {
        Ok(Json(
            Post::find_by_id(id)
                .one(&ctx.db)
                .await?
                .ok_or(AppError::NotFound)?
                .into(),
        ))
    }

    pub async fn update(
        Context(ctx): Context,
        Path(id): Path<i32>,
        Validated(request): Validated<CreatePostRequest>,
    ) -> Result<Json<PostResponse>> {
        let mut post = Post::find_by_id(id)
            .one(&ctx.db)
            .await?
            .ok_or(AppError::NotFound)?
            .into_active_model();
        post.title = Set(request.title);
        Ok(Json(post.update(&ctx.db).await?.into()))
    }

    pub async fn destroy(Context(ctx): Context, Path(id): Path<i32>) -> Result<NoContent> {
        if Post::delete_by_id(id).exec(&ctx.db).await?.rows_affected == 0 {
            return Err(AppError::NotFound);
        }
        Ok(NoContent)
    }
}
```

## 8. Register the routes

Replace `routes/api.rs`. Generator module registration does not implicitly add HTTP routes.
The generated application mounts these paths under `/api` via `App::api_routes`.

<!-- file: routes/api.rs -->
```rust
use crate::app::{
    controllers::post_controller::{PostController, PostResponse},
    requests::create_post_request::CreatePostRequest,
};
use capy::prelude::*;

pub fn routes() -> Routes {
    Routes::new()
        .get("/health", capy::health)
        .operation("health")
        .response::<capy::HealthResponse>()
        .get("/ready", capy::ready)
        .operation("readiness")
        .response::<capy::ReadinessResponse>()
        .error_response::<capy::ReadinessResponse>(503)
        .get("/posts", PostController::index)
        .operation("listPosts")
        .query::<Pagination>()
        .response::<Paginated<PostResponse>>()
        .tag("Posts")
        .error(500)
        .post("/posts", PostController::store)
        .operation("createPost")
        .body::<CreatePostRequest>()
        .created::<PostResponse>()
        .tag("Posts")
        .error(500)
        .get("/posts/{id}", PostController::show)
        .operation("showPost")
        .path::<i32>("id")
        .response::<PostResponse>()
        .error(404)
        .put("/posts/{id}", PostController::update)
        .operation("updatePost")
        .path::<i32>("id")
        .body::<CreatePostRequest>()
        .response::<PostResponse>()
        .error(404)
        .delete("/posts/{id}", PostController::destroy)
        .operation("deletePost")
        .path::<i32>("id")
        .no_content()
        .error(404)
}
```

## 9. Migrate and run

```sh
cargo fmt --check
cargo check --all-targets
capy migrate
capy migrate:status
capy routes --api
capy openapi
capy serve
```

The server listens at `http://127.0.0.1:8000`. `GET /api/health` returns HTTP 200 and
`{"status":"ok"}`. Use `APP_PORT=8001 capy serve` if port 8000 is occupied.

## 10. Call the API

In another terminal, while `capy serve` is running:

```sh
curl -i http://127.0.0.1:8000/api/health
curl -i -X POST http://127.0.0.1:8000/api/posts \
  -H 'Content-Type: application/json' -d '{"title":"Hello, Capy!"}'
curl -i http://127.0.0.1:8000/api/posts
curl -i http://127.0.0.1:8000/api/posts/1
curl -i -X PUT http://127.0.0.1:8000/api/posts/1 \
  -H 'Content-Type: application/json' -d '{"title":"Updated post"}'
curl -i -X POST http://127.0.0.1:8000/api/posts \
  -H 'Content-Type: application/json' -d '{"title":"x"}'
curl -i -X DELETE http://127.0.0.1:8000/api/posts/1
```

On a fresh database, the created ID is `1`; otherwise use the ID returned by POST.
Expect 201 on create, 200 on list/show/update, 422 for the short title, and 204 on
delete. Fetching a deleted ID gives `{"message":"Resource not found"}` with 404.
Every response has `x-request-id`; supply your own valid ID to correlate logs.
Internal database failures receive a sanitized JSON 500.

Stop the server with Ctrl-C. Unix SIGTERM to the `capy serve` PID also shuts down
and reaps its server. In production, run the compiled application binary directly.

## 11. Test the application

Create `tests/posts.rs`. These tests use an isolated in-memory SQLite database,
regardless of the server database chosen above.

<!-- file: tests/posts.rs -->
```rust
use blog::application;
use capy::{prelude::*, testing::TestApp};

#[capy::tokio::test(crate = "capy::tokio")]
async fn posts_are_created_and_validated() -> Result<()> {
    let app = TestApp::boot(application()).await?;
    let created = app
        .post("/api/posts")
        .json(json!({"title": "Hello, Capy!"}))
        .send()
        .await;
    created.assert_created();
    let post: Value = created.json();
    assert_eq!(post["title"], "Hello, Capy!");
    assert!(created.headers.contains_key("x-request-id"));
    app.get("/api/posts").send().await.assert_ok().assert_json(
        json!({"data":[post],"meta":{"page":1,"per_page":20,"total":1,"last_page":1}}),
    );
    app.post("/api/posts")
        .json(json!({"title": "x"}))
        .send()
        .await
        .assert_status(capy::axum::http::StatusCode::UNPROCESSABLE_ENTITY);
    Ok(())
}
```

```sh
cargo fmt --check
cargo clippy --all-targets -- -D warnings
cargo test
```

You can also use `capy test`. To practice migration rollback after stopping the
server, run `capy migrate:rollback`, check `capy migrate:status`, then `capy migrate`
to reapply. Rolling back this migration deletes its table and data.

If you started the disposable PostgreSQL container, remove it when finished:

```sh
docker stop capy-postgres
```

See the [API documentation](https://docs.rs/capy-framework/0.10.0/capy_framework/)
for configuration types and native escape hatches. This release is an initial developer preview.

## 12. Use the contract from React

For a full-stack project, start with `capy new blog` (omit `--api`) and follow the
same Rust steps. `capy types` writes `generated/openapi.json` and
`frontend/src/generated/api-types.ts`. Run `pnpm install --frozen-lockfile` inside
`frontend/` first, or let `capy dev` install dependencies and generate the contracts
after the backend compiles.

```ts
import { api } from '@/lib/api'
import type { CreatePostRequest } from '@/generated/api-types'

const payload: CreatePostRequest = { title: 'Hello, Capy!' }
const post = await api.post('/api/posts', {
  body: payload,
})
const page = await api.get('/api/posts', { params: { query: { page: 1 } } })
await api.delete('/api/posts/{id}', { params: { path: { id: post.id } } })
```

Keep generated files in source control. CI runs `capy types --check` after installing
frontend dependencies, followed by the Rust tests and `pnpm build`. A stale contract
causes a non-zero exit without rewriting files. `capy dev` regenerates after
successful Rust builds, and `capy build` generates before compiling React.

These are compile-time JSON contracts, not runtime response validators. Database
models stay separate from response DTOs. See [API contracts](https://github.com/capy-rs/capy/blob/main/docs/api-contracts.md) for
Serde semantics, validation metadata, API documentation, and custom wire types.