Tutorial: build your first Fexu application¶
This hands-on tutorial creates bookstore, adds a catalog app with a Book model, serves HTML using a Tera template, exposes a named URL and shows the model in the Fexu admin. It follows Fexu's generated layout-2 project structure, not Django's Python file layout.
Version boundary: Start with the published 0.2.0 CLI. The source excerpts are based on the development generator and have not been independently re-executed end-to-end against the published 0.2.0 package in this review. Compare generated files with the exact installed release; for development APIs, use the matching checkout and --fexu-path.
For the published 0.2.0 generator, apply the database URL resolver correction before compiling the generated source.
1. Generate a project¶
Install the published CLI:
cargo install fexu-cli --version 0.2.0 --locked
fexu new project bookstore --template fullstack
cd bookstore
fexu doctor
For a local source build of the upcoming version, install the CLI from the matching Fexu checkout instead, then create your app with --fexu-path. See quickstart.
The generated project already has a runnable application, configuration, templates, static files and empty app registry. You do not create main.rs, base.html or the database driver by hand.
bookstore/
├── Cargo.toml
├── fexu.toml
├── .env.example
├── src/
│ ├── main.rs
│ ├── lib.rs
│ ├── apps.rs
│ └── project/
│ ├── mod.rs
│ ├── settings.rs
│ ├── urls.rs
│ └── management.rs
├── apps/ (new apps appear here)
├── migrations/
├── templates/
│ ├── base.html
│ ├── index.html
│ └── partials/header.html
├── static/css/app.css
└── media/
The generated src/main.rs delegates to bookstore::project::run(), which loads settings, connects to the database, installs registered apps, mounts templates and serves requests.
2. Configure settings¶
File: bookstore/fexu.toml (the following is an excerpt of the generated file):
migrations_dir = "migrations"
schema_command = "cargo run --quiet -- --print-schema"
[project]
name = "bookstore"
template = "fullstack"
layout_version = 2
apps_dir = "apps"
default_locale = "en"
fallback_locale = "en"
[database]
url = "sqlite://db.sqlite3?mode=rwc"
[server]
host = "127.0.0.1"
port = 3000
debug = true
[admin]
enabled = true
embedded_assets = true
site_title = "Bookstore Admin"
site_header = "Bookstore"
[auth]
enabled = true
session_hours = 12
idle_minutes = 30
[templates]
enabled = true
engine = "tera"
templates_dir = "templates"
[branding]
app_name = "Bookstore"
primary_color = "#0f172a"
currency = "EUR"
Keep the other generated sections for [static], [storage], [jobs] and [mail]; the excerpt is not a complete replacement. SQLite is the simplest local start. Production credentials belong in protected environment variables or secrets, not this file. The default server only binds loopback.
File: bookstore/src/project/settings.rs (generated):
pub fn load() -> Result<fexu::migrations::ProjectConfig, Box<dyn std::error::Error>> {
let settings = fexu::migrations::Settings::discover(std::path::Path::new("."))?;
Ok(settings.project().clone())
}
You normally change fexu.toml, not the generated settings loader. Configuration documents the full set of supported settings and environment overrides.
3. Create an app¶
fexu new app catalog
The CLI generates and registers the app. It updates bookstore/src/apps.rs and appends [app.catalog] with its migration directory to bookstore/fexu.toml. You should not duplicate those registrations.
apps/catalog/
├── mod.rs
├── admin.rs
├── urls.rs
├── views.rs
├── models/
│ └── mod.rs
├── migrations/
├── templates/catalog/index.html
└── static/catalog/catalog.css
File: bookstore/apps/catalog/mod.rs (generated by the CLI; it shows how the framework connects your app's parts):
mod admin;
pub mod models;
mod urls;
mod views;
use fexu::apps::{AppConfig, AppError, FexuApplication, Registration, TemplateMode};
pub struct CatalogApp;
impl FexuApplication for CatalogApp {
fn config(&self) -> AppConfig {
AppConfig::new("catalog").prefix("/catalog")
}
fn contribute(&self, registry: &mut Registration<'_>) -> Result<(), AppError> {
let root = registry.project()?.root.clone();
models::register(registry)?;
admin::register(registry)?;
registry.routes(urls::routes()?)?;
registry.migrations("apps/catalog/migrations")?;
registry.templates(root.join("apps/catalog/templates"), TemplateMode::ProjectOverride)?;
registry.static_files(root.join("apps/catalog/static/catalog"))?;
Ok(())
}
}
This corresponds conceptually to registering an application in Django, but Fexu uses Rust's explicit app registry and fexu.toml declarations.
4. Define your first model¶
fexu generate model Book --app catalog
The CLI creates bookstore/apps/catalog/models/book.rs and updates models/mod.rs to register and expose it. The generated fullstack model looks like this:
use fexu::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(FexuModel, Serialize, Deserialize)]
#[fexu(
table = "books",
api = "/api/v1/books",
admin = true,
admin_label = "Book",
permissions = "books"
)]
pub struct Book {
#[field(primary_key, auto)]
pub id: Uuid,
#[field(required, min_length = 1)]
pub name: String,
}
The generated model is registered automatically; it does not require a second manually written register::<Book>() call. The field attributes define the database column contract and validation. To add another field later, first edit the model and then create a new migration. For instance, #[field(min = 0)] pub stock: i64 expresses a nonnegative inventory number; plan an appropriate backfill if existing rows already exist.
See models, relations and database queries for more model types, filters, constraints and CRUD.
5. Generate and run migrations¶
fexu migrate make initial --app catalog
fexu migrate plan
fexu migrate up
fexu migrate status
migrate make writes a migration file to apps/catalog/migrations/. plan compares files and schema without applying changes. up writes the schema, including the framework migrations needed by authentication and jobs. status shows the resulting history.
Always run plan before up when changing an existing database. Do not delete migrations after applying them. See the migration guide.
6. Add a URL and a view¶
The app generator already provides a named route and an HTML view. Learn these generated files before adding more endpoints.
File: bookstore/apps/catalog/urls.rs (the generated file):
use axum::routing::get;
use fexu::urls::{UrlError, UrlSet};
pub fn routes() -> Result<UrlSet, UrlError> {
UrlSet::new().route("catalog.index", "/", get(super::views::index))
}
The app prefix is /catalog, so this route is served at /catalog/. The name catalog.index can be resolved by the Fexu route map.
File: bookstore/apps/catalog/views.rs (the generated file):
use axum::{
Extension,
http::HeaderMap,
response::{Html, IntoResponse, Response},
};
use std::sync::Arc;
pub async fn index(
Extension(catalog): Extension<Arc<fexu::apps::TemplateCatalog>>,
Extension(settings): Extension<Arc<fexu::migrations::ProjectConfig>>,
headers: HeaderMap,
) -> Response {
let context = fexu::pages::home_context(&settings);
match catalog.render("catalog/index.html", &context) {
Ok(html) => Html(html).into_response(),
Err(error) => fexu::views::fail(
&headers,
None,
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
"page.render",
&error.to_string(),
settings.resolved_debug().unwrap_or(false),
),
}
}
This view gets the shared template catalog and settings from request extensions, creates a context and renders an HTML response. It is a regular Axum handler and is connected to the named route via get(super::views::index). This is how Fexu's equivalents of Django's views and URLconf fit together.
Add an extra JSON view¶
Replace bookstore/apps/catalog/urls.rs with:
use axum::routing::get;
use fexu::urls::{UrlError, UrlSet};
pub fn routes() -> Result<UrlSet, UrlError> {
UrlSet::new()
.route("catalog.index", "/", get(super::views::index))?
.route("catalog.status", "/status", get(super::views::status))
}
Append this to bookstore/apps/catalog/views.rs:
pub async fn status() -> Response {
fexu::views::json(&fexu::serde_json::json!({
"app": "catalog",
"ready": true
}))
}
Visiting /catalog/status now returns JSON. Unlike the business-model REST API, this route is explicitly created by your app. It does not query the database or grant access to protected records.
7. Render a real template¶
File: bookstore/apps/catalog/templates/catalog/index.html
Replace the generated heading-only template with:
{% extends "base.html" %}
{% block content %}
<section>
<h1>Welcome to the bookstore</h1>
<p>This page is rendered by the catalog view using Tera.</p>
<p><a href="/catalog/status">Read the catalog status as JSON</a></p>
<p><a href="/admin">Open the administration</a></p>
</section>
{% endblock %}
File: bookstore/templates/base.html (generated layout):
<!doctype html>
<html lang="{{ locale }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ app_name }}</title>
<link rel="stylesheet" href="/static/css/app.css">
</head>
<body>
{% include "partials/header.html" %}
<main>{% block content %}{% endblock %}</main>
</body>
</html>
extends reuses the common layout, block content supplies the page body and include inserts a shared header. Project overrides can customize an app's templates. See templates.
8. Create an administrator and run the server¶
fexu admin create-user --email admin@example.com --staff --superuser
fexu check
cargo check --all-targets
fexu dev
Choose a password at the prompt; there is no default. Open the local address printed by the server (the generated default is http://127.0.0.1:3000). Visit:
/— generated project homepage/catalog/— your catalog template/catalog/status— your JSON view/admin— the administration interface, after signing in/api/v1/books— generated model API, subject to its authentication and permission rules
The fullstack model's permissions = "books" does not make the API anonymously writable. Do not disable authorization to make a tutorial request work. Grant suitable permissions to a user or role if needed. See authentication, permissions and admin.
9. Edit a model safely¶
Suppose the Book model needs a nonnegative stock count. Change bookstore/apps/catalog/models/book.rs by adding:
#[field(min = 0)]
pub stock: i64,
The field belongs inside the Book struct. Then:
fexu migrate make add_stock --app catalog --backfill books.stock:i64=0
fexu migrate plan
fexu migrate up
cargo check --all-targets
Review the generated migration before applying it. The --backfill value gives existing rows an explicit stock value rather than silently dropping data.
10. Where to go next¶
| You want to… | Read |
|---|---|
| Customize project config | Configuration |
| Add model field types or relations | Models and relations |
| Query rows in Rust | Database queries |
| Make advanced URL patterns | URLs |
| Pass different data into HTML | Views and templates |
| Process submitted forms | Forms and validation |
| Secure user routes | Auth and permissions |
| Build business APIs | API and OpenAPI |
| Deploy with Docker/PostgreSQL | Deployment |
| Learn every CLI option | CLI reference |
This tutorial derives its scaffold, model and app code from crates/fexu-cli/src/scaffold.rs, apps.rs and models.rs. The file names and examples are a source-backed walkthrough, not yet a separately executed full tutorial build. The release documentation gate must execute this sequence against the final, version-pinned release candidate.