# 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.
# 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.
```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.
```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.
```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.
```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`.
```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.
```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.