Skip to content

project rulesBackend and APIsrust

Rust Axum Rules

Project rules for Axum web services: shared state, typed extractors, one IntoResponse error type, tower middleware and compile-checked sqlx queries.

npx workspacetemplates add rust-axum-rules --tool claude-code

Writes 1 file to your project root

CLAUDE.mdadd to your file25 lines · 1.4 KBFile
# Project rules: Axum

## Structure
- `main.rs` builds config, the pool and the `Router`; each feature module exposes `pub fn router() -> Router<AppState>` and the app merges or nests them.
- `AppState` is a cloneable struct holding the `PgPool`, config and clients, passed with `.with_state`. Extract it with `State<AppState>`. No `static mut` or lazy globals for dependencies.

## Handlers
- Take typed extractors (`Path`, `Query`, `Json<T>`) with `serde` structs and a validator crate for constraints. Order matters: the body extractor goes last.
- Return `Result<Json<T>, AppError>`.

## Errors
- Define one `AppError` enum with `thiserror` and implement `IntoResponse` mapping each variant to a status and JSON body. Log internal details with `tracing`; return a generic message for 500s.
- Never `unwrap` or `expect` on request-driven paths. Use `?`.

## Middleware
- Apply tower-http layers (`TraceLayer`, `TimeoutLayer`, `CorsLayer`, compression) with `ServiceBuilder`. Put auth in a layer or an extractor.

## Data
- Use `sqlx::query_as!` with offline metadata (`cargo sqlx prepare`) and migrations in `migrations/`. Use transactions for multi-statement changes. Never hold a lock across an `.await`.

## Tests
- Call the router with `tower::ServiceExt::oneshot`. Use `#[sqlx::test]` for database tests.

## Before finishing
Run `cargo fmt --check`, `cargo clippy -- -D warnings` and `cargo test`.

What it does

Axum rewards a clean separation between extractors, handlers and state, but the compiler errors from a mismatched handler can push an agent toward awkward workarounds. These rules describe the shape that compiles cleanly and stays readable.

They set up one error type for the whole service and a clear rule for where sqlx queries live, so failures turn into correct HTTP responses instead of panics.

Example

you › Add GET /projects/{id} returning 404 when missing

agent › The agent adds a handler with a Path extractor, a query_as! lookup, a NotFound variant on AppError, and a oneshot test for both the found and missing cases.

Questions

Which Axum version does it assume?
The 0.7 and 0.8 era APIs, using a plain Router with State and the tokio listener, without older hyper server calls.
Why compile-checked queries?
A wrong column name fails the build instead of a request in production, and the offline files let CI build without a database.
  • ASP.NET Core Web API Rules

    Project rulesdotnet

    Free
  • Django Rules

    Project rulespython

    Free
  • Flask Rules

    Project rulespython

    Free
  • Go Service Rules

    Project rulesgo

    Free