che-rest
Breaking v2 REST layer for che-orm applications.
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:
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 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;
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 processes the schemas of all installed apps and writes one Atlas migration to the
project-level migrations/ directory. This command requires Atlas on the development machine:
Generated migrations are stored under:
migrations/
The database URL is read from [database].url in app.toml. Apply all project migrations with the
built-in SQLite runner; Atlas is not required on the target system:
Do not create model tables from application startup; production servers only apply already-created SQL migrations.