Expand description
Serve JSON:API from axum.
Describe a resource once, and get the wire format for free: the
type/id envelope, relationship linkage, self/related links,
spec-shaped errors with JSON Pointers, and request-body validation.
§One resource, end to end
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use ash_jsonapi::Context;
use ash_jsonapi::crud::{Create, List, Listing, Read, Storage};
use ash_jsonapi::{Page, Query};
use ash_jsonapi::validation::DocumentValidator;
#[derive(Clone)]
struct Todo { id: String, message: String, done: bool }
// Your application state, however you already build it.
#[derive(Clone)]
struct App {
rows: Arc<Mutex<HashMap<String, Todo>>>,
validator: Arc<DocumentValidator>,
}
// Declared once: this writes `TodoSchema`, the `NewTodo` request body and
// its parsing, the serialization, and the JSON Schema bodies are checked
// against. See `resource!` for what each line turns into.
ash_jsonapi::resource! {
Todo as "todo" at "/todos",
state: App,
schema: TodoSchema,
input: NewTodo,
id: id,
attributes: { message: String, done: bool },
}
// Where the validators live. Needed here because this service routes
// CREATE, which has a body to check; a read-only service writes
// `impl Validators for App {}` instead and carries no validator at all.
ash_jsonapi::registry! {
App { validator: Todo }
}
// Your storage. One trait per operation, so you implement only what you
// route — this service creates and reads, so there is no `Update` or
// `Delete` impl anywhere.
impl Storage<Todo> for App {
type Error = String;
}
impl Create<Todo> for App {
// The parsed body arrives as an argument.
async fn create(&self, input: NewTodo, _ctx: &Context) -> Result<Todo, String> {
let mut rows = self.rows.lock().unwrap();
let todo = Todo {
id: format!("t_{}", rows.len() + 1),
message: input.message,
done: input.done,
};
rows.insert(todo.id.clone(), todo.clone());
Ok(todo)
}
}
impl Read<Todo> for App {
async fn get(&self, id: &str) -> Result<Option<Todo>, String> {
Ok(self.rows.lock().unwrap().get(id).cloned())
}
}
impl List<Todo> for App {
// `?page[…]` and `?sort=` arrive parsed; applying them is yours.
async fn list(&self, query: &Query, _ctx: &Context) -> Result<Listing<Todo>, String> {
let rows = self.rows.lock().unwrap();
let total = rows.len();
let Page::Offset { offset, limit } = query.page() else {
return Err("this service pages by offset".into());
};
let page = rows.values().skip(*offset).take(*limit).cloned();
Ok(Listing::new(page).total(total))
}
}
// The routes: `GET|POST /todos` and `GET /todos/{id}`, and nothing else.
ash_jsonapi::api! {
operations: [ash_jsonapi::LIST, ash_jsonapi::CREATE, ash_jsonapi::READ],
resource: Todo,
name: "todo",
path: "/todos",
state: App,
}
let state = App {
rows: Arc::new(Mutex::new(HashMap::new())),
validator: Arc::new(Todo::validator()?),
};
// `layer()` attaches the per-request `Context` every handler needs.
// Without it each request is a 500, so it is not optional.
let app: axum::Router = routes()
.layer(ash_jsonapi::layer())
.with_state(state);
// Then serve it:
// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
// axum::serve(listener, app).await?;That is the whole service. routes() is an axum::Router<App>; name a
different set in operations to expose more or less, and only those
operations’ traits are required — so a service backed by no storage at all
is operations: [READ] over whatever you compute on the fly.
The two macros are independent. resource! writes the wire format and
api! the routes, and either can be replaced by the traits it stands
for — see crud and serialize for the hand-written form, which is
what you want for a computed attribute or a body that is not JSON:API.
§Features
| Feature | Default | What it adds |
|---|---|---|
http | yes | The axum integration: api!, response |
validation | yes | validation::DocumentValidator — request bodies vs. a JSON Schema |
domain | no | ash-domain integration |
audit | yes | audit::Audit — one recorded event per operation |
streaming | no | jsonl — JSONL in and out: the STREAM and INGEST operations |
That is the whole list. TLS, health, metrics, OpenTelemetry, OpenAPI and idempotency are planned rather than shipped, and are deliberately not declared as features until they gate real code — a feature that compiles and does nothing is worse than one that is absent.
With default-features = false you get the document, error and
serialization types alone — no axum, no async runtime.
§Using ash-domain?
Optional, and off by default. Enable the domain feature and
domain_resource! writes the same traits from the schema the domain
already holds — no attribute, type or relationship is restated. Actions
run through the domain’s own pipeline, so policies and extensions apply
and a denial reaches the client as a 403. See crate::domain.
Everything above works with no ash-* crate in the tree; the integration
is a second way in, not the way in.
§Layout
document— the JSON:API wire types.serialize— your data →ResourceObject, driven bySchema.error— spec-shaped errors and their statuses.validation— request-body checking.extract—FromRequest: a request → your types.layer—layer(): the per-requestContextmiddleware.attribute—Attribute: a field’s type, schema and conversions, andFormattedforformat-checked strings.declare—resource!: one declaration, all four impls.query—Query:?page[…]and?sort=, parsed and checked.crud—Resource, the per-operation traits, andapi!.- files —
Uploadin,Downloadout, and theCONTENToperation that routes/{id}/content. jsonl— one resource per line, streamed, for collections too large to be a document.STREAMsends them, selected byAccept;INGESTreads them, selected byContent-Type, answering one result line per input line so a partial batch is visible rather than guessed at.response— axum responses.context— per-request correlation id and principal.macros— the one-liners a handler is made of:not_found!,ensure!,found!,router!,serve!.i18n—Translationkeys on errors, and the negotiatedLocale.hook—before/afteraround every operation; what audit, and later metrics, are built on.audit—Audit: the audit trail, as a hook.
§Shorthand
The macros in macros are sugar over what is above — nothing there is
unreachable by writing the long form. What they buy is that the short form
is also the correct one: an error keeps its correlation id, a router keeps
its layer(), and a server keeps its shutdown signal.
// A guard, a lookup, and the service — three lines that are hard to get
// subtly wrong:
ash_jsonapi::ensure!(!name.is_empty(), ctx, "name must not be empty", "name");
let todo = ash_jsonapi::found!(row, ctx, "no todo with that id");
let app = ash_jsonapi::router!(App, todos::routes()).with_state(state);
ash_jsonapi::serve!("0.0.0.0:3000", app).await?;Re-exports§
pub use attribute::Attribute;pub use attribute::FormatName;pub use attribute::Formatted;pub use context::Context;pub use document::Document;pub use document::ErrorObject;pub use document::ErrorSource;pub use document::Linkage;pub use document::Links;pub use document::MEDIA_TYPE;pub use document::PrimaryData;pub use document::Relationship;pub use document::ResourceIdentifier;pub use document::ResourceObject;pub use error::ErrorCode;pub use error::JsonApiError;pub use i18n::Locale;pub use i18n::Translation;pub use layer::layer;httppub use macros::shutdown_signal;httppub use query::Page;pub use query::Paginator;pub use query::Query;pub use query::Sort;pub use serialize::NoRelationships;pub use serialize::Rel;pub use serialize::RelationshipDef;pub use serialize::Schema;pub use serialize::Serializer;
Modules§
- attribute
- Attribute types: one Rust type, its JSON Schema, and how it is read back.
- audit
audit - An audit trail, as a
Hook. - context
- The per-request
Context. - crud
httpandvalidation - Generated CRUD routes.
- declare
httpandvalidation - Declaring a resource once.
- document
- Pure JSON:API document types.
- domain
domain - Where
ash-domainplugs in — optional, behind thedomainfeature. - error
- JSON:API error objects and their mapping onto HTTP status codes.
- extract
http - Getting a request’s body into your own types.
- hook
beforeandafter— one interception point for every operation.- i18n
- Translation keys on errors, and the negotiated locale on the response.
- jsonl
streaming - JSON Lines: one resource per line, streamed as rows arrive.
- layer
http - The middleware every generated handler needs.
- macros
- Call-site conveniences: the one-liners a handler is mostly made of.
- query
?page[…]and?sort=— parsed, checked, and handed to storage.- response
http - Turning documents and errors into HTTP responses.
- serialize
- Your data + your schema →
ResourceObject. - validation
validation - Validating request documents before they reach your code.
Macros§
- api
httpandvalidation - Generate JSON:API routes for one resource.
- conflict
- A
409— an optimistic-concurrency failure the client may retry. - domain_
api domain - Serve an
ash-domainresource over JSON:API. - domain_
resource domain - ensure
- Return a JSON:API error unless a condition holds.
- ensure_
code - Return an error of a chosen code unless a condition holds.
- forbidden
- A
403— a deliberate denial, not an outage. - found
- Unwrap an
Option, or return a404. - internal_
error - A
500that says nothing to the client. - invalid_
attribute - A
422naming the attribute at fault. - invalid_
parameter - A
400naming the query parameter at fault. - jsonapi_
error - Build a
JsonApiErrorof any code, in a request’s context. - not_
found - A
404, optionally saying what was not found. - registry
httpandvalidation - Implement
Validatorsfrom a list of resources. - resource
httpandvalidation - Declare a resource once: its schema, its serialization, and its parsing.
- resource_
schema domain - Build an
ash_domain::schema::ResourceSchemaliteral. - router
http - Assemble a router from several
api!modules, with the context layer already attached. - serve
http - Bind an address and serve, until the process is asked to stop.
- t
- A
Translationkey with its params.