adelabdelgawad/fullstack-agents/rust-axum-api

Claude Code and agent skill by adelabdelgawad/fullstack-agents

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Rust Axum 0.8 handlers, routers, extractors, middleware, error mapping, JWT auth, WebSocket and graceful shutdown.

Install

npx vskill@latest install adelabdelgawad/fullstack-agents/rust-axum-api

SKILL.md

The same SKILL.md was published earlier as adelabdelgawad/fullstack-agents/rust-axum-api.

Axum 0.8 API Patterns

The HTTP layer of a Rust service. Handlers are THIN: extract, call one use case, map the result. Business logic lives in application (see rust-clean-architecture).

Path Syntax — Axum 0.8 CRITICAL

rust
Router::new()
.route("/users/{id}", get(get_user)) // {id} — Axum 0.8+
.route("/files/{*path}", get(serve_file)) // wildcard
// .route("/users/:id", ...) // FORBIDDEN: panics AT RUNTIME

:id does not fail at compile time — it panics when the router is built. This is the #1 Axum migration foot-gun. Always {name}.

Extractor Ordering

Extractors implementing FromRequestParts (State, Path, Query, headers) can go in any position. Body-consuming extractors (Json, Form, Bytes, String) must be LAST — there is only one body.

rust
async fn create_user(
State(state): State<AppState>, // app state — any position
Path(id): Path<Uuid>, // params — any position
Json(payload): Json<CreateUserDto>, // body consumer — ALWAYS LAST
) -> Result<Json<UserDto>, ApiFailure> {
let dto = application::identity::use_cases::create_user(
&state.pool, state.users.as_ref(), state.hasher.as_ref(), payload,
).await?;
Ok(Json(dto))
}
  • State<T> for application state (pools, ports, config) — composes via FromRef

for sub-states. Extension<T> ONLY for per-request data injected by middleware (e.g. authenticated Claims). Never Extension for app state.

  • TypedHeader lives in axum-extra, not axum.

Error Mapping (IntoResponse)

One newtype wraps AppError at the HTTP boundary:

rust
// apps/api/src/error.rs
pub struct ApiFailure(pub AppError);
impl From<AppError> for ApiFailure { fn from(e: AppError) -> Self { Self(e) } }
impl IntoResponse for ApiFailure {
fn into_response(self) -> Response {
let status = match &self.0 {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::Validation(_) | AppError::Domain(_) => StatusCode::UNPROCESSABLE_ENTITY,
AppError::Conflict(_) => StatusCode::CONFLICT,
AppError::Unauthorized => StatusCode::UNAUTHORIZED,
AppError::Forbidden => StatusCode::FORBIDDEN,
AppError::Internal(detail) => {
tracing::error!(%detail, "internal error"); // log detail
StatusCode::INTERNAL_SERVER_ERROR // hide detail
}
};
(status, Json(shared::ApiError::from(self.0))).into_response()
}
}

Never unwrap()/expect() in handlers — ? with ApiFailure. Never leak sqlx::Error or internal messages in responses.

Middleware

rust
let app = Router::new()
.route("/users/{id}", get(get_user))
.route_layer(middleware::from_fn_with_state(state.clone(), require_auth))
.route("/healthz", get(|| async { "ok" })) // outside auth
.layer(ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(TimeoutLayer::new(Duration::from_secs(30)))
.layer(CompressionLayer::new()))
.with_state(state);
  • route_layer applies only to routes registered SO FAR (unmatched paths still

404 without running it); layer wraps everything including fallback. Auth goes on route_layer of protected routes; tracing/timeout on outer layer.

  • ServiceBuilder order: first listed = outermost.
  • Never block in middleware — spawn_blocking for CPU-bound work.
JWT auth middleware (cookie or bearer)
rust
pub async fn require_auth(
State(state): State<AppState>,
mut req: Request, next: Next,
) -> Result<Response, ApiFailure> {
let token = extract_token(&req).ok_or(AppError::Unauthorized)?;
let claims = state.jwt.verify(&token)?; // AppError::Unauthorized on fail
req.extensions_mut().insert(claims); // Extension<Claims> downstream
Ok(next.run(req).await)
}

Claims carry identity only (sub, jti, exp, iat, iss, aud) — never roles or business fields; authorization is resolved server-side per request.

WebSocket

rust
async fn ws_handler(ws: WebSocketUpgrade, State(state): State<AppState>) -> Response {
ws.on_upgrade(|socket| handle_socket(socket, state))
}
  • Rooms via tokio::sync::broadcast channels.
  • Heartbeat: server pings on an interval; drop the connection on missed pongs.
  • Handle Message::Close explicitly — never ignore close frames.

Graceful Shutdown

rust
axum::serve(listener, app.into_make_service())
.with_graceful_shutdown(async { tokio::signal::ctrl_c().await.ok(); })
.await?;

Forbidden Patterns

PatternWhy
:id path syntaxRuntime panic in Axum 0.8 — use {id}
Body extractor not lastCompiles in some orders, breaks — keep Json/Form last
Extension for app stateState + FromRef is type-checked at router build
unwrap/expect in handlersPropagate with ? into ApiFailure
Business logic in handlersExtract → one use case → map; nothing else
sqlx::Error in response typesMap through RepoError → AppError → ApiError
Blocking calls in handlers/middlewaretokio::task::spawn_blocking
Missing WebSocket heartbeatProxies kill idle connections silently

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
1
7-day trend score
0

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/adelabdelgawad/fullstack-agents/rust-axum-api/badge)](https://verified-skill.com/skills/adelabdelgawad/fullstack-agents/rust-axum-api)

Something wrong with this skill or its page? Tell us.