Skip to main content

Module jsonapi

Module jsonapi 

Source
Expand description

JSON:API v1.1 response envelope adapter — wrap a flat serde_json::Value (typical serializer output) into the {"data": {"type", "id", "attributes": {...}}} shape that JSON:API clients expect. See jsonapi::to_resource + jsonapi::to_collection. JSON:API v1.1 response shape adapter.

Converts a flat serde_json::Value (typical output of crate::serializer) into the JSON:API envelope:

{
  "data": {
    "type": "posts",
    "id":   "42",
    "attributes": { "title": "...", "body": "..." }
  }
}

Or for collections:

{
  "data": [
    { "type": "posts", "id": "1", "attributes": {...} },
    { "type": "posts", "id": "2", "attributes": {...} }
  ],
  "meta": { "count": 2 }
}

Most apps wire it as a thin handler-side helper:

use rustango::jsonapi::{to_resource, to_collection};

async fn show_post(...) -> Json<Value> {
    let s = PostSerializer::from_model(&post);
    Json(to_resource("posts", &s.id.to_string(), s.to_value()))
}

async fn list_posts(...) -> Json<Value> {
    let posts: Vec<PostSerializer> = PostSerializer::many(&rows);
    let docs: Vec<_> = posts.iter()
        .map(|p| (p.id.to_string(), p.to_value()))
        .collect();
    Json(to_collection("posts", &docs))
}

§What this does NOT cover (yet)

  • relationships — the spec lets you express FKs/M2Ms inline; for now, embed via attributes or use included (helpers below).
  • Sparse fieldsets, sorting, filtering — those live in your ViewSet / handler, not this adapter.
  • Errors envelope — use crate::problem_details for RFC 7807 (clean, widely-supported alternative).

Functions§

resource_object
Produce the inner {"type", "id", "attributes"} object — useful when you’re hand-building a response with included/meta/etc.
to_collection
Wrap a collection of resources. docs is [(id, attributes), ...]. Adds meta.count for free so clients can size pagers.
to_resource
Wrap a single resource into the JSON:API top-level {"data": …}. id is always rendered as a string per the spec.
with_included
Add included to an existing resource doc. The new doc is merged into doc["included"] (creating it if absent). Per the spec, included is an array of full resource objects — pass them already-shaped via resource_object.
with_meta
Add an arbitrary meta field merged into the existing meta object. Useful for pagination cursors, totals, ETags, etc.