che-rest
Breaking v2 REST layer for che-orm applications.
The library targets che-orm 0.3. Database connection methods are async;
REST viewsets and image actions currently require models with i64 primary keys.
The current v2 surface is the typed ORM2 CRUD router. A viewset builds its
database-independent queryset in get_queryset; database access happens only
when the queryset is materialized:
use ;
let app = new
.install
.build
.await?;
The migration plan is documented in docs/ORM2_MIGRATION_PLAN.md.
The minimal migrated example is available under todo_api:
Start a Project
Create a new runnable che-rest application:
cargo-generate Template
Use the standalone che-rest-template repository
to generate a minimal project with cargo-generate:
See that repository for its requirements and complete setup instructions.
When developing against local checkouts with the built-in project generator, point the generated project at them:
The generated project includes app.toml, a server entrypoint, an apps::installed_apps() registry,
and a local manage binary. Create the first app with:
Path overrides are useful for this repo layout:
../che-rest
../che-orm
Include the built-in auth module in the generated app registry:
A complete runnable example with CRUD, authentication, WebSocket signals, internal channels,
TypeScript generation, and Vue admin generation is available in
examples/cli_fullstack.
For a minimal SQLite todo API, see the step-by-step
Todo API From Scratch tutorial.
Management
Applications define one installed app list and use it for both the API server and management commands:
use InstalledApps;
Common management commands:
OpenAPI is served by the running application at /api/openapi.json by default, and follows custom
Server::api_prefix(...) values.
Server startup:
let app = new
.install
.build
.await?;
Server startup does not create model tables. Generate and apply migrations before starting the server:
Image fields
Install che_rest::media::module() alongside auth to serve authenticated files under
/api/media/{key} (or the configured API prefix). che_orm::ImageField is a
TEXT-backed relative storage key, not a URL or a BLOB; Option<ImageField>
is nullable. The field is always read-only in JSON writes, even without an
explicit #[serializer(read_only)]. Register an image action once in the
owning ViewSet; che-rest then creates the upload/replace and clear endpoints:
use ImageField;
use ;
// In the model: pub avatar: Option<ImageField>,
// In the ViewSet's configure():
config.image_field?;
For a ViewSet registered at /users, this adds PUT and DELETE at
/api/users/{id}/images/avatar/. PUT takes a multipart file and replaces
the image; DELETE clears it. Both operations appear in OpenAPI and the
generated TypeScript client (userApi.avatar.replace(id, file) and
userApi.avatar.clear(id)). By default, the handlers use the ViewSet's
permissions and object queryset. authorize, before, and write callbacks
allow field-specific rules: a self-only avatar, a scene-version check held
through saving, or additional model metadata. Configure them explicitly when
the default ViewSet write permission is inappropriate.
ImageCreateEndpoint similarly adds a multipart POST /api/{resource}/upload/
for images that are new records, such as attachments. Its application
callback validates extra form fields and creates domain links; on failure the
framework removes the new file. The generated client sends optional extra
fields as Record<string, string | Blob>. Neither form accepts a storage key
from the client.
The media service's read_image_field limits multipart parts;
ImageStorage::save checks the actual JPEG/PNG/GIF/WebP format, decodes the
image and enforces byte and dimension limits. An
ImagePolicy::thumbnail(max_dimension) re-encodes a bounded PNG. Without it,
the validated original bytes are retained (including animated GIFs).
replace writes a new file, compares the previously read image key with the
current database key, then updates the model. A stale write returns 409 and
discards its new file. The write callback can include related metadata such
as the avatar URL, MIME type and size in that same conditional database update.
clear uses the same check. Application callbacks remain responsible for
domain-specific checks such as diagram revision matching; they do not implement
the HTTP upload flow.
JSON responses serialize ImageField as its storage key. generate-ts emits
string | null for nullable image fields, and generated admin metadata marks
them as images. A browser can form an image URL using the configured API base
plus /media/ and the returned key. A ViewSet can register ImageCleanup in
configure() to remove the file after a direct ViewSet deletion. An async
prepare_delete_async hook can collect keys before a parent record cascades;
after_delete then removes them. Post-commit failures are queued in
.pending-image-deletions and retried on startup or later uploads: a committed
DELETE must not return 500 because file cleanup failed. Raw SQL deletes do
not run ViewSet hooks and need separate orphan cleanup. With no [media]
section, the storage root is uploads. To override it in app.toml:
[]
= "/var/lib/my-app/uploads"
Back up this directory separately from the SQLite database.
The generated app.toml also configures the listener and API prefix:
[]
= "127.0.0.1"
= 3000
= "/api"
The application entrypoint reads these values, so changing the bind address, port, or API prefix does not require editing Rust code.
Installed app routes are served under /api by default. A viewset registered as "/users" is exposed as /api/users.
Swagger UI is exposed at /api/ and the OpenAPI JSON schema at /api/openapi.json.
Writable foreign-key fields can be exposed separately from nested read-only output. Use
#[serializer(foreign_key = User, relation = TaskAssigneeRelation)] on a scalar Option<i64>
field. The generated admin uses an async relation selector, while nested fields such as
Task.author remain read-only response data.
Typed ViewSets
Generated and custom viewsets use associated types for their detail/write serializer, list serializer, queryset, filters, and permissions:
use ;
;
;
Register a typed viewset with viewset_with; it uses ViewSet::path() for the router, model schema,
and API metadata:
ctx.viewset_with;
ListSerializer is required on every ViewSet. Set it to Self::Serializer when list and detail
responses have the same fields. To return fewer fields from the list, derive a separate
ModelSerializer for the same model and use it instead:
Both serializers must accept the queryset's item type. GET /tasks/ uses ListSerializer;
GET /tasks/{id}/ and write responses use Serializer. OpenAPI describes separate list-item
and detail schemas. generate-ts gives list() a distinct TaskListItem result type when
the fields differ, while retrieve() retains Task. The generated admin uses list fields for
table columns and detail fields for forms. Regenerate the clients after changing either serializer.
FilterSetSpec types must implement Default. Built-in permissions include AllowAny,
IsAuthenticated, and IsAdminUser.
The Model derive generates compile-time-safe field constants on the model type. Use those constants
when declaring filters:
static TASK_FILTERS: & = &;
The model type is part of Filter<M>, so a filter for one model cannot be accidentally used in
another model's FilterSet. Filter::exact_as("assignee", Task::ASSIGNEE_ID) can be used
when the public query name should differ from the database field name. Query builders also accept
typed fields directly:
query
.filter
.all
.await?;
Relations use serializer attributes with generated ORM2 relation markers:
pub author: UserSerializer,
Fields populated by the server should be read-only in the serializer and assigned in the viewset's write preparation hook:
Breaking API Changes
ORM writes use generated field descriptors: use .set(Task::NAME, value) instead of string field
names. Serializer validation returns ValidatedWrite; viewset prepare_* hooks can add server-owned
fields before ValidatedWrite::save(database) persists the change.
Auth
che-rest includes an optional auth app. Install it to resolve token credentials and add a
request-scoped CurrentPrincipal to request extensions. Its auth_user() is always the built-in
framework user:
Create the first superuser:
Then create the first superuser:
The command reads app.toml by default. Use --config path/to/app.toml to select another
configuration file. The auth users table must exist before running the command.
Get a token with the Django REST Framework compatible endpoint:
Use the returned token for API requests:
Authorization: Token <token>
Authentication is optional at the middleware level. Protect a typed viewset by selecting
type Permission = IsAuthenticated; unauthenticated requests then receive 401. Use
AllowAny for public viewsets and IsAdminUser for administrator-only viewsets.
Application User
Applications can define one domain profile model related to auth::User. Configure an async
resolver when the application state is created; the resolved model is stored only on the current
request.
pub async
let state = from_config_file
.await?
.with_current_user_resolver;
Keep the type recovery and the authorization error in one application function:
Viewsets and permissions then only call that function:
let profile = current_profile?;
Profile is never part of che-rest; it is defined and resolved by the application. If the
resolver returns None, the request remains framework-authenticated; only application code that
calls current_profile requires a profile.
Generate the typed TypeScript client from installed app metadata:
The generator writes api_client.ts, channels.ts, models.ts, api.ts, useModelList.ts, and
useModelItem.ts; it also writes auth.ts when the auth app is installed. It does not scan Rust
source files or require the HTTP server to be running.
Generated TypeScript clients expose setAuthToken(token) in api_client.ts.
WebSocket Signals
Install the channel module. The WebSocket endpoint is available at /api/ws/ under the configured
API prefix:
WebSocket clients subscribe only to declared public signals. CRUD viewsets can opt in to lifecycle
signals by overriding ViewSet::signal_access; the default names are <resource>.created,
<resource>.updated, and <resource>.deleted. The default lifecycle payload is
{ "id": <primary key> }; clients that need current object data should reload it through the REST
endpoint, so viewset permissions still apply. Nested resource names use dots, for example
/auth/users maps to auth.users.created when lifecycle signals are enabled. Modules can declare
additional signals in init:
Publish a declared signal with:
state.signals.publish;
Modules can create separate internal application channels through AppState::app_channels(), which
are never exposed to WebSocket clients:
let channels = state.app_channels.clone;
let app = new
.install
.build
.await?;
channels.publish;
Modules subscribe to internal channels in subscribe, before any module start hooks publish
initial events. Both hooks run after the database schema is ready:
;
Application channels use bounded broadcast queues. A slow subscriber receives Lagged and should
resynchronize as needed. They are only available inside the server process.
Internal events can have multiple handlers; all of them run in independent application-channel subscriptions. Public WebSocket signals are independent from internal application channels.
Connections must be authenticated. Non-browser clients can provide Authorization: Token <token>
during the WebSocket upgrade. Browser WebSocket connections use the existing same-origin session
cookie, because the browser API cannot attach an Authorization header.
The TypeScript generator creates channels.ts with a cookie-authenticated ChannelClient:
import { ChannelClient } from "./generated/channels";
const channels = new ChannelClient({
onMessage: (event) => console.log(event.signal, event.payload),
onError: (event) => console.error(event.code, event.detail),
});
await channels.connect();
channels.subscribe("orders.created");
The client derives /api/ws/ from VITE_API_BASE_URL, converting http to ws and https to
wss. Browser cookies are sent automatically for same-origin connections.
Subscribe and unsubscribe using text JSON frames:
const socket = ;
socket.;
socket.;
Clients cannot subscribe to undeclared signals. Private user signals can be published with
publish_user and use user:{id}:<signal> names; only that user can subscribe after the signal has
been created by server-side publication. Signal names may contain ASCII letters, numbers, :, -,
_, and .. The server confirms subscription changes with subscribed and unsubscribed messages.
This is in-memory pub/sub for one server process: messages are delivered only to currently connected
clients, are not persisted, and do not cross process boundaries. A slow receiver receives a lagged
error when messages are dropped; it does not receive a replay.
Cookie Sessions
Token authentication and cookie sessions can be enabled together. Sessions use an HttpOnly
cookie and a readable CSRF cookie. For same-origin applications, add optional configuration:
[]
= "che_rest_session"
= "csrf_token"
= 604800
= 86400 # renew active sessions during their final day
= 2592000 # require login again after 30 days
= false # set true when serving over HTTPS
= "Lax"
Login with a session cookie:
Unsafe requests made with a session must include the value from the csrf_token cookie in
the X-CSRF-Token header. Token-authenticated requests do not require CSRF validation.
Project-local src/bin/manage.rs:
use Management;
use apps;
async
Create a new app module in src/apps/<name>:
By default startapp creates one model from the app name. If the app name ends with
app, that suffix is removed first, so taskapp creates model Task.
Pass one or more --model options to generate specific models:
Generated tables use <app>_<model_snake_case> names, for example taskapp_task.
Routes use the model snake-case without adding an s, for example /api/task/.
Generated files:
src/apps/
mod.rs
taskapp/
mod.rs
models.rs
serializers.rs
filters.rs
views.rs
The generated serializers.rs, filters.rs, and views.rs use the typed API shown above;
the app module registers each generated viewset with ctx.viewset_with(...).
Then add the app to apps::installed_apps():
new.add
Create migrations for all installed apps. The optional positional value names the generated migration:
Generate TypeScript models and API client from installed app metadata:
This writes:
src/generated/
api_client.ts
channels.ts
models.ts
api.ts
useModelList.ts
useModelItem.ts
The OpenAPI document describes CRUD routes registered with ModuleContext::viewset and
viewset_with, including list filters, limit, offset, and ordering query
parameters. A ViewSet can add reusable behavior through ViewSetExtension instances in
ViewSet::configure(). Extension routes, OpenAPI operations, and generated TypeScript methods
are registered from the same operation descriptors.
The same schema is also served by running applications at /api/openapi.json, with
Swagger UI available at /api/ by default.
Generate a standalone Vue admin project from installed app metadata:
This writes a Vite + Vue + Bootstrap project:
frontend/admin/
package.json
index.html
vite.config.ts
tsconfig.json
.env.example
src/
main.ts
App.vue
router.ts
admin/
AdminApp.vue
AdminLogin.vue
AdminModelList.vue
AdminModelTable.vue
AdminModelForm.vue
adminRoutes.ts
admin.css
adminSchema.ts
components/
GenericModelTable.vue
GenericModelForm.vue
pages/
UserList.vue
UserForm.vue
generated/
adminSchema.ts
adminRoutes.ts
generated/
api_client.ts
channels.ts
models.ts
api.ts
useModelList.ts
useModelItem.ts
The first run creates the full project and one editable list/form page pair for each model.
Later runs update generated files and create missing model pages, but leave existing Vue, CSS,
config, package, and model page files untouched so local admin customizations are preserved.
Use --force to overwrite static project files from templates:
The generated admin uses session-cookie authentication through /api-session-auth/login/ and
requires che_rest::auth::module() to be installed. The generated Vite dev server proxies /api
and /api-session-auth/ to http://127.0.0.1:3000 by default. Configure the backend target and
relative API URLs with Vite env variables:
VITE_API_TARGET=http://127.0.0.1:3000
VITE_API_BASE_URL=/api
VITE_AUTH_URL=/api-session-auth/login/
VITE_LOGOUT_URL=/api-session-auth/logout/
Static files are copied from the framework's canonical admin templates. Dynamic files are regenerated from installed app metadata:
Canonical templates are stored in the repository under src/admin/templates/. Change those files
when changing the framework default admin UI; examples/cli_fullstack/frontend/admin/ is generated
output and is not the template source.
src/admin/generated/adminSchema.ts, src/admin/generated/adminRoutes.ts, the compatibility shim
src/admin/adminSchema.ts, and src/generated/*.
Per-model pages in src/admin/pages are generated as thin wrappers around the generic CRUD
components. Customize those page files for model-specific fields, actions, and layout; they are
not overwritten on later runs unless --force is passed.
Defaults:
--name auto
makemigrations compares installed app schemas with the compiled migration history and writes
reviewable Rust migration modules under src/migrations/<app>/. It does not invoke an external
migration tool:
Generated migrations are stored under:
src/migrations/<app>/
The database URL is read from [database].url in app.toml. Apply all project migrations with the
built-in forward-only SQLite executor:
Do not create model tables from application startup; production servers only apply already-created SQL migrations.
Compiled forward-only migrations
Management::migrations(...) supplies the project registry, usually through
Management::new(apps).migrations(project::migrations::all()). An empty registry is valid while
generating the first migration. Management has no SQL-file migration fallback.
Preview pending compiled migrations before applying them:
The plan lists migrations in dependency order, their dependencies and operations,
and warnings for table/column deletion, column changes and manual SQL. It validates
the registered graph, applied checksums, dependency history and historical state.
SQLite is opened read-only; a missing database is treated as empty and is not
created. No migrations or history records are written. The command requires a
file database path (plain or sqlite://) and cannot be combined with a migrate
subcommand. It previews compiled migrations; SQL execution and live-schema
compatibility are checked when applying them. Rebuild after changing migration
sources, and inspect RunSql source before applying manual SQL.
Inspect the SQLite SQL for one registered migration without opening a database:
sqlmigrate rebuilds only the selected migration's dependency state in memory,
then prints its SQLite statements. Declarative table changes therefore show the
same create-copy-drop-rename SQL used by the executor. RunSql is printed as
authored. The command requires compiled migrations and does not validate the
live database schema or execute any statement.
List registered compiled migrations and their database status with:
[X] marks a migration recorded in che_migration_history; [ ] marks a
pending migration. Dependencies are listed beneath each migration. The command
opens a file database only in read-only mode, treats a missing database as an
empty history and never creates the history table.
Apply a selected application's forward migration target with:
The first two forms select the application's single latest migration. The executor applies only that target and its missing dependencies, each in a separate atomic SQLite transaction; unrelated pending migrations are left untouched. A target already passed by a later migration in the same application is rejected because rollback is not supported. Unknown applications and migration names are also rejected before the database is opened.
When two reviewed branches create compatible heads for one application, create an empty merge migration with:
The command accepts exactly two heads. It rebuilds their common historical
state, replays the two branches in both orders, and creates a migration that
depends on both heads only when the resulting declarative states agree. It
rejects RunSql, conflicting operations, and three or more heads; resolve
those with an explicit reviewed migration. Use --dry-run to inspect generated
Rust before the file and registry are changed.
For example, generate an application's migration with:
The writer creates m0001_initial.rs and a managed section of mod.rs containing
module declarations and pub fn all() -> Vec<che_orm::Migration>. Declare the
migrations module in the owning application and pass its collector to management:
new
.migrations
.run
.await?;
For multiple applications, concatenate their all() results. Rebuild the
management binary after generation. Existing handwritten mod.rs files must
have // che-orm: migrations begin and // che-orm: migrations end markers;
the writer owns the declarations and collector inside those markers. Keep
handwritten code outside them, and avoid another all() in the same module.
--empty produces zero operations even when models differ from history.
Normal generation rejects conflicting branches and cross-application references
whose target table or field is not yet present in compiled migration history.
Generate and register the target application's migration first. Operations are
ordered and replayed in memory before writing; unsupported dependency sequences
require an explicit migration.
When SQLite must rebuild a table, generated migrations temporarily drop and
restore declared triggers and views that reference it, including objects owned
by other applications. The definitions are taken from compiled migration
history. Review the generated operations before applying them, and rebuild
manage after generation.
Use makemigrations <app> --check in CI: it exits with an error when the
installed models have changes without a compiled migration. Use --dry-run to
print the prospective Rust source without changing files. Before either command
creates a migration, it compares m000N_*.rs files with the compiled registry;
if a prior generation has not been rebuilt yet, it stops and asks for a rebuild.
For a new project whose applications contain cyclic cross-application foreign keys, omit the app name and provide a directory that will contain one directory per application:
This empty-history batch mode writes each app's 0001_initial without the
cross-application FKs, then writes 0002_relationships migrations that depend
on both initial migrations. Rebuild after generation and combine each app's
migrations::all() when constructing Management.
New migration files are created exclusively. Registry updates use a directory
lock and atomic replacement. A competing writer fails without overwriting files.
An interrupted process may leave .che-migrations.lock or .che-mod.rs.tmp;
inspect the directory and confirm no writer is active before removing them.