Skip to main content

Crate ash_jsonapi

Crate ash_jsonapi 

Source
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

FeatureDefaultWhat it adds
httpyesThe axum integration: api!, response
validationyesvalidation::DocumentValidator — request bodies vs. a JSON Schema
domainnoash-domain integration
audityesaudit::Audit — one recorded event per operation
streamingnojsonl — 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

§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::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;http
pub use macros::shutdown_signal;http
pub 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.
auditaudit
An audit trail, as a Hook.
context
The per-request Context.
crudhttp and validation
Generated CRUD routes.
declarehttp and validation
Declaring a resource once.
document
Pure JSON:API document types.
domaindomain
Where ash-domain plugs in — optional, behind the domain feature.
error
JSON:API error objects and their mapping onto HTTP status codes.
extracthttp
Getting a request’s body into your own types.
hook
before and after — one interception point for every operation.
i18n
Translation keys on errors, and the negotiated locale on the response.
jsonlstreaming
JSON Lines: one resource per line, streamed as rows arrive.
layerhttp
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.
responsehttp
Turning documents and errors into HTTP responses.
serialize
Your data + your schema → ResourceObject.
validationvalidation
Validating request documents before they reach your code.

Macros§

apihttp and validation
Generate JSON:API routes for one resource.
conflict
A 409 — an optimistic-concurrency failure the client may retry.
domain_apidomain
Serve an ash-domain resource over JSON:API.
domain_resourcedomain
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 a 404.
internal_error
A 500 that says nothing to the client.
invalid_attribute
A 422 naming the attribute at fault.
invalid_parameter
A 400 naming the query parameter at fault.
jsonapi_error
Build a JsonApiError of any code, in a request’s context.
not_found
A 404, optionally saying what was not found.
registryhttp and validation
Implement Validators from a list of resources.
resourcehttp and validation
Declare a resource once: its schema, its serialization, and its parsing.
resource_schemadomain
Build an ash_domain::schema::ResourceSchema literal.
routerhttp
Assemble a router from several api! modules, with the context layer already attached.
servehttp
Bind an address and serve, until the process is asked to stop.
t
A Translation key with its params.