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 viaattributesor useincluded(helpers below).- Sparse fieldsets, sorting, filtering — those live in your ViewSet / handler, not this adapter.
- Errors envelope — use
crate::problem_detailsfor RFC 7807 (clean, widely-supported alternative).
Functions§
- resource_
object - Produce the inner
{"type", "id", "attributes"}object — useful when you’re hand-building a response withincluded/meta/etc. - to_
collection - Wrap a collection of resources.
docsis[(id, attributes), ...]. Addsmeta.countfor free so clients can size pagers. - to_
resource - Wrap a single resource into the JSON:API top-level
{"data": …}.idis always rendered as a string per the spec. - with_
included - Add
includedto an existing resource doc. The new doc is merged intodoc["included"](creating it if absent). Per the spec,includedis an array of full resource objects — pass them already-shaped viaresource_object. - with_
meta - Add an arbitrary
metafield merged into the existing meta object. Useful for pagination cursors, totals, ETags, etc.