jsonapi_core 0.2.1

A typed JSON:API v1.1 serialization library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
#![warn(missing_docs)]
//! # jsonapi_core
//!
//! A typed [JSON:API v1.1](https://jsonapi.org/format/) serialization library for Rust.
//!
//! `jsonapi_core` gives you a complete type model for JSON:API documents — resources,
//! relationships, links, errors — with a derive macro that handles the envelope format
//! so you work with plain Rust structs. It also provides a query builder, content
//! negotiation, sparse fieldset filtering, and a registry for resolving `included`
//! resources.
//!
//! # Defining a Resource
//!
//! Use `#[derive(JsonApi)]` to map a Rust struct to a JSON:API resource. Fields become
//! attributes by default. Annotate relationships, meta, and links explicitly.
//!
//! ```
//! # #[cfg(feature = "derive")] {
//! use jsonapi_core::{JsonApi, Relationship};
//!
//! #[derive(Debug, Clone, PartialEq, JsonApi)]
//! #[jsonapi(type = "articles")]
//! struct Article {
//!     #[jsonapi(id)]
//!     id: String,
//!     title: String,
//!     body: String,
//!     #[jsonapi(relationship, type = "people")]
//!     author: Relationship<Person>,
//! }
//!
//! #[derive(Debug, Clone, PartialEq, JsonApi)]
//! #[jsonapi(type = "people")]
//! struct Person {
//!     #[jsonapi(id)]
//!     id: String,
//!     name: String,
//! }
//! # }
//! ```
//!
//! # Serializing
//!
//! Wrap a resource in a [`Document`] and serialize with serde. The derive macro produces
//! the JSON:API envelope (`type`, `id`, `attributes`, `relationships`).
//!
//! ```
//! # #[cfg(feature = "derive")] {
//! # use jsonapi_core::{JsonApi, Relationship, Document, PrimaryData, Identity,
//! #     RelationshipData, ResourceIdentifier, ResourceObject};
//! # #[derive(Debug, Clone, PartialEq, JsonApi)]
//! # #[jsonapi(type = "articles")]
//! # struct Article {
//! #     #[jsonapi(id)]
//! #     id: String,
//! #     title: String,
//! #     body: String,
//! #     #[jsonapi(relationship, type = "people")]
//! #     author: Relationship<Person>,
//! # }
//! # #[derive(Debug, Clone, PartialEq, JsonApi)]
//! # #[jsonapi(type = "people")]
//! # struct Person {
//! #     #[jsonapi(id)]
//! #     id: String,
//! #     name: String,
//! # }
//! let article = Article {
//!     id: "1".into(),
//!     title: "JSON:API paints my bikeshed!".into(),
//!     body: "The shortest article. Ever.".into(),
//!     author: Relationship::new(RelationshipData::ToOne(Some(ResourceIdentifier {
//!         type_: "people".into(),
//!         identity: Identity::Id("9".into()),
//!         meta: None,
//!     }))),
//! };
//!
//! let doc: Document<Article> = Document::Data {
//!     data: PrimaryData::Single(Box::new(article)),
//!     included: vec![],
//!     meta: None,
//!     jsonapi: None,
//!     links: None,
//! };
//!
//! let json = serde_json::to_string_pretty(&doc).unwrap();
//! assert!(json.contains("\"type\": \"articles\""));
//! # }
//! ```
//!
//! # Deserializing and the Registry
//!
//! Parse a JSON:API response and use the [`Registry`] to look up included resources.
//! [`Document<P>`](Document) is generic over the primary type `P` and, separately, the
//! included type (which defaults to [`Resource`] so mixed `included` arrays Just Work).
//! Write `Document<Article>` for a typed primary with dynamic included, `Document<Resource>`
//! for fully dynamic, or `Document<Article, Article>` for a homogeneous typed document.
//!
//! ```
//! # #[cfg(feature = "derive")] {
//! use jsonapi_core::{JsonApi, Document, PrimaryData, Resource, ResourceObject};
//!
//! #[derive(Debug, Clone, PartialEq, JsonApi)]
//! #[jsonapi(type = "people")]
//! struct Person {
//!     #[jsonapi(id)]
//!     id: String,
//!     name: String,
//! }
//!
//! let json = r#"{
//!     "data": {
//!         "type": "articles", "id": "1",
//!         "attributes": {"title": "Hello JSON:API"},
//!         "relationships": {
//!             "author": {"data": {"type": "people", "id": "9"}}
//!         }
//!     },
//!     "included": [{
//!         "type": "people", "id": "9",
//!         "attributes": {"name": "Dan Gebhardt"}
//!     }]
//! }"#;
//!
//! let doc: Document<Resource> = serde_json::from_str(json).unwrap();
//! let registry = doc.registry().unwrap();
//!
//! // Typed lookup — deserializes the stored Value into a Person
//! let author: Person = registry.get_by_id("people", "9").unwrap();
//! assert_eq!(author.name, "Dan Gebhardt");
//! # }
//! ```
//!
//! # Document Accessors
//!
//! Pattern-matching on [`Document`] and [`PrimaryData`] for the common single-primary
//! case is verbose. The accessors on [`Document`] do the unwrap for you and return
//! [`Error::UnexpectedDocumentShape`] when the shape is wrong:
//!
//! - [`Document::into_single`] / [`Document::into_many`] / [`Document::into_meta`] — consuming.
//! - [`Document::as_single`] / [`Document::as_many`] / [`Document::primary`] / [`Document::included`] — borrowing.
//! - [`Document::from_str`] / [`Document::from_slice`] / [`Document::from_value`] —
//!   parse with a structural pre-pass that surfaces
//!   [`Error::TypeMismatch`], [`Error::MalformedRelationship`],
//!   [`Error::MissingAttribute`], and [`Error::IncludedRefMissing`]
//!   as typed errors instead of `serde_json::Error` strings.
//!
//! ```
//! # use jsonapi_core::{Document, Resource, ResourceObject};
//! let json = r#"{"data":{"type":"articles","id":"1","attributes":{"title":"Hi"}}}"#;
//! let doc: Document<Resource> = serde_json::from_str(json).unwrap();
//!
//! let article = doc.into_single().unwrap();
//! assert_eq!(article.resource_type(), "articles");
//! assert_eq!(article.resource_id(), Some("1"));
//! ```
//!
//! # Resource-Level `links` and `meta`
//!
//! When a resource carries a `#[jsonapi(links)]` or `#[jsonapi(meta)]` field,
//! the derive auto-implements the [`HasLinks`] / [`HasMeta`] traits so
//! consumers can read those blocks uniformly without pattern-matching on
//! concrete types. Resources without those fields do *not* implement the
//! traits — the absence is part of the type's contract.
//!
//! ```
//! # #[cfg(feature = "derive")] {
//! use jsonapi_core::{HasMeta, JsonApi, Meta};
//!
//! #[derive(Debug, Clone, PartialEq, JsonApi)]
//! #[jsonapi(type = "articles")]
//! struct Article {
//!     #[jsonapi(id)]
//!     id: String,
//!     title: String,
//!     #[jsonapi(meta)]
//!     extra: Option<Meta>,
//! }
//!
//! fn meta_count<R: HasMeta>(r: &R) -> usize {
//!     r.meta().map(|m| m.len()).unwrap_or(0)
//! }
//! # }
//! ```
//!
//! # Working with Relationships
//!
//! [`Relationship<T>`] and [`Identity`] expose small helper methods so consumers
//! don't need to `match` on the `#[non_exhaustive]` variants directly.
//!
//! - [`Relationship::ids()`](Relationship::ids) — iterator of server-assigned IDs, regardless of cardinality.
//! - [`Relationship::first_id()`](Relationship::first_id) — the first server id (or `None` for null / empty / lid-only).
//! - [`Relationship::first_id_or_lid()`](Relationship::first_id_or_lid) — the first identifier of either kind.
//! - [`Relationship::single_id()`](Relationship::single_id) — type-checked to-one access; errors on null, lid-only, or to-many.
//! - [`Relationship::identifiers()`](Relationship::identifiers) — unified slice view of all identifiers.
//! - [`Identity::as_id()`](Identity::as_id) / [`Identity::as_lid()`](Identity::as_lid) — `Option<&str>` accessors.
//!
//! # Dynamic Resources
//!
//! When you don't know the schema at compile time, use [`Resource`] as an open-set
//! fallback. It stores attributes as `serde_json::Value` and relationships as a
//! `HashMap`.
//!
//! ```
//! use jsonapi_core::{Document, PrimaryData, Resource, ResourceObject};
//!
//! let json = r#"{"data": {"type": "widgets", "id": "42", "attributes": {"color": "red"}}}"#;
//! let doc: Document<Resource> = serde_json::from_str(json).unwrap();
//!
//! if let Document::Data { data: PrimaryData::Single(widget), .. } = &doc {
//!     assert_eq!(widget.resource_type(), "widgets");
//!     assert_eq!(widget.attributes["color"], "red");
//! }
//! ```
//!
//! # Recursive Resolver
//!
//! The [`Registry::resolve()`] method produces kitsu-core-style flattened output:
//! attributes are hoisted onto the resource, relationships are resolved and inlined
//! recursively, and the JSON:API envelope is stripped.
//!
//! ```
//! use jsonapi_core::{Document, Registry, ResolveConfig, Resource};
//!
//! let json = r#"{
//!     "data": {
//!         "type": "articles", "id": "1",
//!         "attributes": {"title": "Hello"},
//!         "relationships": {
//!             "author": {"data": {"type": "people", "id": "9"}}
//!         }
//!     },
//!     "included": [{
//!         "type": "people", "id": "9",
//!         "attributes": {"name": "Dan"}
//!     }]
//! }"#;
//!
//! let doc: Document<Resource> = serde_json::from_str(json).unwrap();
//! let registry = doc.registry().unwrap();
//! let value: serde_json::Value = serde_json::to_value(&doc).unwrap();
//! let data = &value["data"];
//!
//! let flat = registry.resolve(data, &ResolveConfig::default());
//! assert_eq!(flat["title"], "Hello");
//! assert_eq!(flat["author"]["name"], "Dan");
//! ```
//!
//! # Sparse Fieldsets
//!
//! Use [`FieldsetConfig`] to filter which fields appear in serialized output.
//! Two paths are available: [`SparseSerializer`] wraps a typed resource, and
//! [`sparse_filter()`] operates on a raw `serde_json::Value` document.
//!
//! ```
//! # #[cfg(feature = "derive")] {
//! # use jsonapi_core::{JsonApi, Relationship, Identity, RelationshipData,
//! #     ResourceIdentifier, FieldsetConfig, SparseSerializer, ResourceObject};
//! # #[derive(Debug, Clone, PartialEq, JsonApi)]
//! # #[jsonapi(type = "articles")]
//! # struct Article {
//! #     #[jsonapi(id)]
//! #     id: String,
//! #     title: String,
//! #     body: String,
//! #     #[jsonapi(relationship, type = "people")]
//! #     author: Relationship<Person>,
//! # }
//! # #[derive(Debug, Clone, PartialEq, JsonApi)]
//! # #[jsonapi(type = "people")]
//! # struct Person {
//! #     #[jsonapi(id)]
//! #     id: String,
//! #     name: String,
//! # }
//! # let article = Article {
//! #     id: "1".into(), title: "Hello".into(), body: "World".into(),
//! #     author: Relationship::new(RelationshipData::ToOne(Some(ResourceIdentifier {
//! #         type_: "people".into(), identity: Identity::Id("9".into()), meta: None,
//! #     }))),
//! # };
//! // Only include the "title" field for articles
//! let config = FieldsetConfig::new().fields("articles", &["title"]);
//! let json = serde_json::to_value(SparseSerializer::new(&article, &config)).unwrap();
//!
//! assert_eq!(json["attributes"]["title"], "Hello");
//! assert!(json["attributes"].get("body").is_none());
//! # }
//! ```
//!
//! # Include Path Validation
//!
//! [`TypeRegistry`] stores static type metadata and validates that include paths
//! are traversable through the relationship graph.
//!
//! ```
//! # #[cfg(feature = "derive")] {
//! # use jsonapi_core::{JsonApi, Relationship, TypeRegistry, ResourceObject};
//! # #[derive(Debug, Clone, PartialEq, JsonApi)]
//! # #[jsonapi(type = "articles")]
//! # struct Article {
//! #     #[jsonapi(id)]
//! #     id: String,
//! #     title: String,
//! #     #[jsonapi(relationship, type = "people")]
//! #     author: Relationship<Person>,
//! # }
//! # #[derive(Debug, Clone, PartialEq, JsonApi)]
//! # #[jsonapi(type = "people")]
//! # struct Person {
//! #     #[jsonapi(id)]
//! #     id: String,
//! #     name: String,
//! # }
//! let mut registry = TypeRegistry::new();
//! registry.register::<Article>();
//!
//! // "author" is a valid include path from articles
//! assert!(registry.validate_include_paths("articles", &["author"]).is_ok());
//!
//! // "editor" is not a relationship on articles
//! assert!(registry.validate_include_paths("articles", &["editor"]).is_err());
//! # }
//! ```
//!
//! # Query Builder
//!
//! [`QueryBuilder`] produces JSON:API-compliant query strings with correct bracket
//! encoding and RFC 3986 percent-encoding.
//!
//! ```
//! use jsonapi_core::QueryBuilder;
//!
//! let qs = QueryBuilder::new()
//!     .include(&["author", "comments"])
//!     .fields("articles", &["title", "body"])
//!     .filter("published", "true")
//!     .sort(&["-created", "title"])
//!     .page("number", "1")
//!     .build();
//!
//! assert!(qs.contains("include=author,comments"));
//! assert!(qs.contains("fields[articles]=title,body"));
//! assert!(qs.contains("filter[published]=true"));
//! ```
//!
//! # Case Conversion
//!
//! The derive macro generates fuzzy deserialization aliases for all common case
//! variants of each field name. Output casing is controlled by [`CaseConvention`]
//! via the `#[jsonapi(case = "...")]` attribute.
//!
//! ```
//! use jsonapi_core::{CaseConvention, CaseConfig};
//!
//! let config = CaseConfig { member_case: CaseConvention::CamelCase };
//! assert_eq!(config.member_case.convert("first_name"), "firstName");
//! assert_eq!(CaseConvention::KebabCase.convert("firstName"), "first-name");
//! assert_eq!(CaseConvention::None.convert("first_name"), "first_name");
//! ```
//!
//! # Content Negotiation
//!
//! Validate incoming `Content-Type` headers and negotiate `Accept` headers per the
//! JSON:API 1.1 protocol.
//!
//! ```
//! use jsonapi_core::{validate_content_type, negotiate_accept, JsonApiMediaType};
//!
//! // Validate a Content-Type header (rejects unknown parameters)
//! let mt = validate_content_type("application/vnd.api+json").unwrap();
//! assert!(mt.ext.is_empty());
//!
//! // Negotiate an Accept header (returns server capabilities)
//! let response = negotiate_accept(
//!     "application/vnd.api+json, application/json",
//!     &[],  // server extensions
//!     &[],  // server profiles
//! ).unwrap();
//! assert_eq!(response.to_header_value(), "application/vnd.api+json");
//! ```
//!
//! # Atomic Operations
//!
//! The [`atomic`] module (feature `atomic-ops`) implements the JSON:API
//! [Atomic Operations extension](https://jsonapi.org/ext/atomic/) for bundling
//! add/update/remove operations into a single request.
//!
//! ```
//! # #[cfg(feature = "atomic-ops")] {
//! use std::collections::BTreeMap;
//! use jsonapi_core::{
//!     atomic::{AtomicOperation, AtomicRequest, OperationTarget, ATOMIC_EXT_URI},
//!     PrimaryData, Resource,
//! };
//!
//! let req = AtomicRequest {
//!     operations: vec![AtomicOperation::Add {
//!         target: OperationTarget::default(),
//!         data: PrimaryData::Single(Box::new(Resource {
//!             type_: "articles".into(),
//!             id: None,
//!             lid: Some("a1".into()),
//!             attributes: serde_json::json!({"title": "Hello"}),
//!             relationships: BTreeMap::new(),
//!             links: None,
//!             meta: None,
//!         })),
//!     }],
//! };
//!
//! assert_eq!(ATOMIC_EXT_URI, "https://jsonapi.org/ext/atomic");
//! let json = serde_json::to_string(&req).unwrap();
//! assert!(json.contains("\"op\":\"add\""));
//! req.validate_lid_refs().unwrap();
//! # }
//! ```
//!
//! # Member Name Validation
//!
//! Validate member names at runtime per JSON:API 1.1 rules. The derive macro also
//! performs compile-time validation of type strings and `#[jsonapi(rename)]` values.
//!
//! ```
//! use jsonapi_core::{validate_member_name, MemberNameKind};
//!
//! // Standard member name
//! assert!(matches!(validate_member_name("first-name"), Ok(MemberNameKind::Standard)));
//!
//! // @-member (extension namespaced)
//! match validate_member_name("@ext:comments").unwrap() {
//!     MemberNameKind::AtMember { namespace, member } => {
//!         assert_eq!(namespace, "ext");
//!         assert_eq!(member, "comments");
//!     }
//!     _ => unreachable!(),
//! }
//!
//! // Invalid: empty string
//! assert!(validate_member_name("").is_err());
//! ```
//!
//! # Feature Flags
//!
//! | Feature | Default | Description |
//! |---------|---------|-------------|
//! | `derive` | yes | Re-exports `#[derive(JsonApi)]` from `jsonapi_core_derive` |
//! | `atomic-ops` | no | Atomic Operations extension types (`atomic` module) |

pub mod case;
pub mod error;
pub mod fieldset;
pub mod media_type;
pub mod model;
pub mod query;
pub mod registry;
pub mod type_registry;
pub mod validation;

#[cfg(feature = "atomic-ops")]
pub mod atomic;

pub use case::{CaseConfig, CaseConvention};
pub use error::{Error, Result};
pub use fieldset::{FieldsetConfig, SparseSerializer, sparse_filter};
pub use media_type::{JsonApiMediaType, negotiate_accept, validate_content_type};
pub use model::{
    ApiError, Document, ErrorLinks, ErrorSource, HasLinks, HasMeta, Hreflang, Identity,
    JsonApiObject, Link, LinkObject, Links, Meta, PrimaryData, Relationship, RelationshipData,
    Resource, ResourceIdentifier, ResourceObject,
};
pub use query::QueryBuilder;
pub use registry::{Registry, ResolveConfig};
pub use type_registry::{TypeInfo, TypeRegistry};
pub use validation::{MemberNameKind, validate_member_name};

#[cfg(feature = "atomic-ops")]
pub use atomic::{
    ATOMIC_EXT_URI, AtomicOperation, AtomicRequest, AtomicResponse, AtomicResult, OperationRef,
    OperationTarget,
};

#[cfg(feature = "derive")]
pub use jsonapi_core_derive::JsonApi;