REST Macro - Opinionated API Builder
Note: This project is currently very much in progress and under active development. APIs will change, and features are incomplete.
A Rust library providing an opinionated higher-level macro wrapper for Actix Web and SQLx, designed for rapid API prototyping.
Features
- Zero-boilerplate REST APIs: Create complete CRUD endpoints with a single derive macro
- Typed write DTOs: The derive macro and
.eonmacro both generateCreateandUpdatepayload types - Compile-time
.eonservices: Generate strongly typed resources and DTOs from a minimal.eonservice file - Migration generation: Generate explicit SQL migrations from
.eonservice definitions - Field validation: Enforce string length and numeric range constraints in generated handlers and OpenAPI
- Stable error envelope: Generated resource handlers return JSON errors with
code,message, and optionalfield - Typed list queries: Generated collection routes support typed
limit,offset,sort,order, exact-matchfilter_<field>params, and paged response envelopes - Built-in authentication: JWT-based authentication with role management
- Role-Based Access Control: Declarative protection for your endpoints with role requirements
- Database Agnostic: Currently defaults to SQLite, with plans to support all SQLx targets
- Relationship Handling: Define foreign keys and nested routes between resources
- Referential Actions: Configure relation delete behavior with
Cascade,Restrict,SetNull, orNoAction
Installation
CLI
Install the vsr command-line tool from crates.io:
If you are working from a checkout of this repository, the workspace defaults to the CLI package,
so a plain root build produces target/release/vsr:
Use cargo build --workspace when you want all workspace crates, or
cargo build -p very_simple_rest when you want only the library package.
Library
You can include this library in your project by adding it as a git dependency in your Cargo.toml:
Note that you need to add the other dependencies aswell
[]
= { = "https://github.com/MatiasHiltunen/very_simple_rest.git" }
= { = "1", = ["derive"] }
= { = "0.7", = ["macros", "runtime-tokio", "sqlite"] }
= "4"
= "0.10"
= "0.4"
Examples
The code includes example project demo. To run it, clone the repo and run from project's root:
Quick Start
use *;
async
Authentication
The library provides these authentication endpoints out of the box:
- POST /api/auth/register - Register a new user
- POST /api/auth/login - Login and get a JWT token
- GET /api/auth/me - Get information about the authenticated account
Built-in auth failures now also use the shared JSON error envelope. For example, invalid login returns:
When you create built-in admin users through vsr create-admin or vsr setup, the CLI now
inspects the live user table and also populates numeric claim columns such as tenant_id,
org_id, or claim_workspace_id. Interactive flows prompt for those values, and non-interactive
flows accept environment variables named ADMIN_<COLUMN_NAME>, such as ADMIN_TENANT_ID=1.
JWT Secret Configuration
Built-in auth now requires JWT_SECRET to be set before the server starts.
Supported sources:
- Environment variable:
JWT_SECRET=your_secret_here .envfile in your project root:JWT_SECRET=your_secret_here
The runtime no longer generates a random fallback secret, so tokens remain valid across restarts and multi-instance deployments only when you provide an explicit secret.
Example login:
User Management
The library provides two methods for creating admin users:
1. Environment Variables (Non-Interactive)
Set these environment variables before starting your application:
ADMIN_EMAIL=admin@example.com
ADMIN_PASSWORD=securepassword
ADMIN_TENANT_ID=1
After the built-in auth schema has been migrated, ensure_admin_exists can create the first admin
user automatically with these credentials. If the user table also has numeric claim columns such
as tenant_id, org_id, or claim_workspace_id, ensure_admin_exists now reads matching
ADMIN_<COLUMN_NAME> variables and stores them on the admin row too.
2. CLI Tool (Interactive)
The library includes a CLI tool for managing your API, with specific commands for user management:
# Generate a migration for the built-in auth schema
# Emit a standalone Rust server project from a bare .eon service
# Build a server binary directly from a bare .eon service
# Setup wizard with interactive prompts
# Create an admin user
# Create an admin with specific credentials
# Check database status including admin users
# Generate a .env template file
The CLI tool provides a secure way to set up admin users with password confirmation and validation.
When you run vsr from a directory containing exactly one .eon file, commands such as setup,
create-admin, check-db, and gen-env now auto-discover that service and derive the default
database URL from it.
For detailed instructions on using the CLI tool, see the CLI Tool Documentation.
Server Generation
The CLI can also turn a bare .eon service definition into a runnable Actix server project or a
compiled binary:
# Generate a local Rust project you can inspect and edit
# Build a binary directly from the same .eon file
The emitted project includes:
Cargo.tomlwith the required runtime dependenciessrc/main.rswired torest_api_from_eon!- the copied
.eonfile .env.exampleopenapi.jsonmigrations/0000_auth.sqlwith built-in auth enabled by defaultmigrations/0001_service.sql
Built-in auth and account routes are enabled by default for generated servers and documents. Use
--without-auth if your .eon service defines its own user table or if you want to omit the
shared /auth routes and migrations/0000_auth.sql.
vsr build <service.eon> now writes the binary into the current directory by default, naming it
after the .eon file stem. For example, vsr build blog_api.eon produces ./blog-api. If
--output points to an existing directory, the binary is placed inside that directory using the
same default name.
The build command also exports the generated runtime assets next to the binary in
<binary>.bundle/, including .env.example, openapi.json, the copied .eon file,
README.md, migrations/, and relative TLS certificate files when they exist at build time.
When runtime.compression.static_precompressed = true, vsr build also generates .br and
.gz companion files for copied static assets inside that bundle.
Generated server projects serve the OpenAPI document at /openapi.json and a Swagger UI page at
/docs.
When a .eon service defines static mounts, vsr server emit also copies those directories into
the generated project so the emitted server can serve them without extra setup.
When a .eon service defines security, vsr server emit also applies the compiled JSON body
limits, CORS policy, trusted-proxy handling, auth rate limits, security headers, and built-in
auth token settings automatically in the emitted server.
When a .eon service defines tls, vsr server emit also wires Rustls-based HTTPS with HTTP/2
in the emitted server, defaults BIND_ADDR to 127.0.0.1:8443, and lets you generate local
certificate PEM files with vsr tls self-signed.
vsr server emit also carries the compiled .eon database engine config into the generated
project. SQLite services now default to encrypted database.engine = TursoLocal, using
var/data/<module>.db and TURSO_ENCRYPTION_KEY unless you override it explicitly. You can still
opt back into the legacy runtime path with database.engine.kind = Sqlx.
OpenAPI
You can also render an OpenAPI document directly from either a .eon file or derive-based Rust
sources:
# Generate OpenAPI JSON from a bare .eon service
# Generate the same kind of document from #[derive(RestApi)] resources
# Omit built-in auth and account routes if your service owns the user model
The current generator covers generated resource routes, DTO schemas, nested collection routes, JWT
bearer auth, the /api server base URL, and built-in auth/account routes by default. Use
--without-auth to omit them. In Swagger, login and registration appear under Auth, while the
current-user endpoint appears under Account. Generated server projects reuse the same document.
Collection and nested collection routes also document their typed list query parameters and their
paged response envelopes, including pagination, sorting, cursor pagination, exact-match field
filters, total, next_offset, and next_cursor.
.eon Reference Docs
You can generate a Markdown reference for the full currently supported .eon surface:
The generated document is intended to be precise enough for AI agents and still readable for
humans. The checked-in reference lives at docs/eon-reference.md.
Static Files In .eon
Bare .eon services can configure static file serving at the service level:
module: "static_site_api"
static: {
mounts: [
{
mount: "/assets"
dir: "public/assets"
mode: Directory
cache: Immutable
}
{
mount: "/"
dir: "public"
mode: Spa
index_file: "index.html"
fallback_file: "index.html"
cache: NoStore
}
]
}
resources: [
{
name: "Page"
fields: [
{ name: "title", type: "String" }
]
}
]
Supported static mount options:
mount: URL prefix such as/assetsor/dir: directory relative to the.eonfilemode:DirectoryorSpaindex_file: optional directory index file, defaulting toindex.htmlforSpafallback_file: SPA fallback target, defaulting toindex.htmlforSpacache:NoStore,Revalidate, orImmutable
The loader validates that:
- static directories stay under the
.eonservice root - reserved routes such as
/api,/auth,/docs, and/openapi.jsonare not shadowed - SPA fallback only applies to
GETandHEADHTML navigations, not missing asset files - symlinked directories are rejected during emitted-project copying
Database Engine In .eon
Bare .eon services can also define a service-level database engine. For SQLite services, the
default when this block is omitted is:
database: {
engine: {
kind: TursoLocal
path: "var/data/<module>.db"
encryption_key_env: "TURSO_ENCRYPTION_KEY"
}
}
You can still override it explicitly:
database: {
engine: {
kind: TursoLocal
path: "var/data/app.db"
encryption_key_env: "TURSO_ENCRYPTION_KEY"
}
}
Current support:
Sqlx: the legacy runtime path; use this explicitly if you want plain SQLx SQLite for a SQLite.eonserviceTursoLocal: bootstraps a local Turso database file and uses the project runtime database adapter with SQLite-compatible SQLTursoLocal.encryption_key_env: reads a hex key from the named environment variable and uses Turso local encryption with the current default cipher (aegis256) during bootstrap
Current limitation:
- This is still a project-local runtime adapter, not a true upstream SQLx
Anydriver.
TLS In .eon
Bare .eon services can also enable Rustls-based HTTPS for generated Actix servers:
tls: {
cert_path: "certs/dev-cert.pem"
key_path: "certs/dev-key.pem"
cert_path_env: "TLS_CERT_PATH"
key_path_env: "TLS_KEY_PATH"
}
Notes:
- When
tlsis present, generated servers bind with Rustls and enable HTTP/2 automatically. - Relative certificate paths are resolved from the emitted project directory, or from
<binary>.bundle/for built binaries. vsr tls self-signed --config service.eongenerates compatible local PEM files using those configured paths. With a single.eonfile in the current directory,vsr tls self-signedauto-discovers it.BIND_ADDRdefaults to127.0.0.1:8443for TLS-enabled services.
Security In .eon
Bare .eon services can also define service-level server security defaults:
security: {
requests: {
json_max_bytes: 1048576
}
cors: {
origins: ["http://localhost:3000"]
origins_env: "CORS_ORIGINS"
allow_credentials: true
allow_methods: ["GET", "POST", "OPTIONS"]
allow_headers: ["authorization", "content-type"]
expose_headers: ["x-total-count"]
max_age_seconds: 600
}
trusted_proxies: {
proxies: ["127.0.0.1", "::1"]
proxies_env: "TRUSTED_PROXIES"
}
rate_limits: {
login: { requests: 10, window_seconds: 60 }
register: { requests: 5, window_seconds: 300 }
}
headers: {
frame_options: Deny
content_type_options: true
referrer_policy: StrictOriginWhenCrossOrigin
hsts: {
max_age_seconds: 31536000
include_subdomains: true
}
}
auth: {
issuer: "very_simple_rest"
audience: "public-api"
access_token_ttl_seconds: 3600
}
}
Supported security options:
requests.json_max_bytes: JSON body limit for generated resource and built-in auth routescors.origins: explicit allowed origins, or["*"]when credentials are disabledcors.origins_env: optional comma-separated origin list loaded from an environment variablecors.allow_credentials: emitsAccess-Control-Allow-Credentials: truecors.allow_methods: allowed preflight methods, defaulting to common REST verbs when omittedcors.allow_headers: allowed request headers, defaulting toauthorization,content-type, andacceptcors.expose_headers: response headers exposed to the browsercors.max_age_seconds: optional preflight cache durationtrusted_proxies.proxies: exact proxy IPs whose forwarded headers should be trustedtrusted_proxies.proxies_env: optional comma-separated trusted proxy IP list loaded from envrate_limits.login: built-in auth login rate limit by resolved client IPrate_limits.register: built-in auth registration rate limit by resolved client IPheaders.frame_options:DenyorSameOriginheaders.content_type_options: emitsX-Content-Type-Options: nosniffheaders.referrer_policy: values such asNoReferrerorStrictOriginWhenCrossOriginheaders.hsts: optionalStrict-Transport-Securityconfigurationauth.issuer: built-in auth JWTissclaimauth.audience: built-in auth JWTaudclaimauth.access_token_ttl_seconds: built-in auth token lifetime
Generated .eon modules expose the compiled settings through module::security() and
module::configure_security(...). Secrets such as JWT_SECRET still belong in the environment,
not in .eon. The current rate-limit implementation is in-memory and process-local, so it is a
good default for a single binary but not a shared distributed limiter.
Runtime In .eon
.eon services can also define service-level runtime defaults:
runtime: {
compression: {
enabled: true
static_precompressed: true
}
}
Generated .eon modules expose this through module::runtime(). The currently parsed runtime
options are:
compression.enabled: enables dynamic HTTP response compression on emitted servers and can be applied manually withvery_simple_rest::core::runtime::compression_middleware(&module::runtime())compression.static_precompressed: enables.brand.gzcompanion-file lookup for generated static mounts, addsVary: Accept-Encoding, and preserves the existing cache policy when an encoded asset is served
vsr build now generates those companion files into <binary>.bundle/ when this flag is enabled.
vsr server emit still copies the source static directories as-is.
Migrations
Generated REST resources no longer run CREATE TABLE IF NOT EXISTS at startup. For .eon
services, generate explicit SQL and apply it before serving traffic:
# Generate the built-in auth migration
# Generate migrations from Rust `#[derive(RestApi)]` resources
# Generate an additive migration between two schema versions
# Inspect a live database against a schema source
# Generate a deterministic migration file from a .eon service
# Verify that the checked-in SQL still matches the .eon schema
# Apply migrations to the configured database
# Or derive the database URL from a bare .eon service, including TursoLocal paths
The generated SQL includes:
CREATE TABLEstatements for each resource- Foreign keys for declared relations
- Indexes for relation fields and row-policy fields
Built-in auth now has the same explicit schema path:
vsr migrate authgenerates theusertable migrationvsr setupapplies that auth migration before prompting for the first admin userensure_admin_existsno longer creates tables at server startup
Derive-based resources can now use the same flow:
vsr migrate derive --input src --output migrations/...scans Rust sources for#[derive(RestApi)]--exclude-table useravoids colliding with the built-in auth migration when your project also exposesUservsr migrate check-deriveverifies checked-in SQL against the current Rust resource definitions
For additive schema evolution, vsr migrate diff compares two schema sources and emits only:
- new tables
- new indexes
- safe added columns that are nullable or have generated timestamp defaults
It intentionally rejects destructive or ambiguous changes such as removed fields, type changes, required backfilled columns, or new relation columns. Those still require a manual SQL migration.
For live databases, vsr migrate inspect compares the current schema to a .eon file, a Rust
source file, or a Rust source directory and reports missing tables, missing columns, missing
indexes, foreign-key target drift, ON DELETE drift, type/nullability mismatches, and missing
timestamp defaults.
For a larger SQLite benchmark fixture with deep relations and a deterministic seed script, see
examples/sqlite_bench/.
For a policy-heavy .eon example with tenant claims, owner-scoped writes, and self-scoped
resources, see examples/fine_grained_policies/.
For a minimal .eon-only app with built-in auth, owner-scoped todos, admin visibility across all
rows, and a static browser client, see examples/todo_app/.
For a real-world single-.eon example with public catalog discovery, built-in account
management, admin-curated thesis topics, owner-scoped collaboration requests, and a same-origin
browser client, see examples/bridgeboard/.
RBAC Attributes
Protect your endpoints with declarative role requirements:
This will:
- Allow users with the "user" role to read data
- Restrict update/delete operations to users with the "admin" role
- Return 403 Forbidden if the user lacks the required role
Row Policies
Portable row-level policies can be generated at the macro layer. They work for SQLite too, because the generated handlers enforce them in application code instead of relying on database-native RLS.
For derive-based resources:
This makes the generated handlers:
- Filter reads to rows owned by the authenticated user
- Bind
user.idintouser_idon create - Prevent ownership changes through update payloads
- Return
404for update/delete when the row is outside the caller's scope
The same attribute also supports claim-based scoping and explicit admin bypass control:
This makes the generated handlers:
- Read
tenant_idfrom the JWT claims inUserContext - Force
user_idandtenant_idon create, regardless of request payload - Keep tenant-scoped fields out of generated
Create/UpdateDTOs - Apply the same tenant filter to admin users when
admin_bypass = false
When you use the built-in auth routes, /auth/login now emits numeric claims automatically from
the user row:
- Any numeric column ending in
_idbecomes a claim with the same name, such astenant_idororg_id - Any numeric column named
claim_<name>becomes a claim named<name>
That lets claim-scoped policies work without a custom token issuer, as long as your user records carry the relevant columns.
Relationships
Define relationships between entities:
pub post_id: i64,
This generates nested routes like /api/post/{post_id}/comment automatically.
Relation delete behavior is schema-driven and ends up in the generated foreign key:
CascadeRestrictSetNullNoAction
SetNull is only allowed on nullable foreign-key fields.
Custom relation column renames are not supported. The Rust field name is the database column name.
Validation
Generated Create and Update handlers can enforce field-level validation before SQL execution.
Derive example:
.eon example:
{
name: "Post"
fields: [
{ name: "id", type: I64 }
{
name: "title"
type: String
validate: {
min_length: 3
max_length: 120
}
}
{
name: "score"
type: I64
validate: {
minimum: 1
maximum: 10
}
}
]
}
Supported constraints:
min_lengthandmax_lengthfor string-like fieldsminimumandmaximumfor integer and floating-point fields
These constraints are reflected in generated OpenAPI schemas as minLength, maxLength,
minimum, and maximum.
Error Responses
Generated resource handlers now use a stable JSON error body for validation and common CRUD failures:
The current resource-level envelope fields are:
codemessagefieldfor field-specific validation failures
Generated collection routes also accept typed query parameters:
limitandoffsetfor paginationcursor=<token>for keyset paginationsort=<field>andorder=asc|descfor safe sortingfilter_<field>=...for exact-match filtering on generated resource fields
Per-resource page defaults and caps can be configured from either generation path:
resources: [
{
name: "Post"
list: {
default_limit: 25
max_limit: 100
}
fields: [
{ name: "id", type: I64 }
{ name: "title", type: String }
]
}
]
Collection responses now return a metadata envelope instead of a bare JSON array:
Unknown query keys, invalid typed values, and unsupported combinations such as offset without
limit return the same JSON error envelope with invalid_query or invalid_pagination. When a
resource has max_limit configured, oversized limit values are capped to that maximum rather
than rejected. Cursor tokens are opaque, URL-safe strings; they cannot be combined with offset,
sort, or order, because they already encode the current keyset position and sort direction.
OpenAPI documents expose this as ApiErrorResponse and use it for generated 400, 403, 404,
and 500 resource responses where applicable. Built-in auth routes use the same envelope for
login failures, duplicate registration, and token/authentication failures.
Malformed JSON bodies now also use the same envelope, for example:
Invalid path and query parsing now use the same contract too, with codes like:
invalid_pathinvalid_query
EON Service Macro
You can also generate a typed REST module from a .eon file at compile time:
use *;
rest_api_from_eon!;
async
Minimal .eon schema:
resources: [
{
name: "Post"
roles: {
read: "user"
create: "user"
update: "user"
delete: "user"
}
policies: {
admin_bypass: false
read: [
"user_id=user.id"
{ field: "tenant_id", equals: "claim.tenant_id" }
]
create: [
"user_id=user.id"
{ field: "tenant_id", value: "claim.tenant_id" }
]
update: [
"user_id=user.id"
{ field: "tenant_id", equals: "claim.tenant_id" }
]
delete: { field: "tenant_id", equals: "claim.tenant_id" }
}
fields: [
{ name: "id", type: I64 }
{ name: "title", type: String }
{ name: "content", type: String }
{ name: "user_id", type: I64 }
{ name: "created_at", type: String }
{ name: "updated_at", type: String }
]
}
]
Relations in .eon support the same delete actions:
{
name: "Comment"
fields: [
{ name: "id", type: I64 }
{
name: "post_id"
type: I64
relation: {
references: "post.id"
nested_route: true
on_delete: Cascade
}
}
{ name: "body", type: String }
]
}
This generates:
blog_api::Postblog_api::PostCreateblog_api::PostUpdateblog_api::configure
The workspace uses the eon crate for parsing. For formatting .eon files, install the external formatter:
Roadmap
- Support for all SQLx database backends
- More flexible role definitions
- Custom validation rules
- Richer OpenAPI response metadata and more detailed validation/error schemas
Contributions
Contributions are welcome! Feel free to submit issues and pull requests.
AI Assistance
This library has been built with assistance from OpenAI's o4 and Anthropic's Claude 3.5 Sonnet.
License
MIT