Crate jsonapi_rs

source ·
Expand description

This is documentation for the jsonapi-rs crate. The crate is meant to be used for serializing, deserializing and validating JSON:API requests and responses.

Examples

Basic Usage with Macro

Using the jsonapi_model! macro a struct can be converted into a JsonApiDocument or Resource. It is required that the struct have an id property whose type is String. The second argument in the jsonapi_model! marco defines the type member as required by the JSON:API specification


use serde::{Deserialize, Serialize};
use jsonapi_rs::jsonapi_model;
use jsonapi_rs::model::{JsonApiModel,Relationships,Resources};
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Flea {
    id: String,
    name: String,
}

jsonapi_model!(Flea; "flea");

let example_flea = Flea {
    id: "123".into(),
    name: "Mr.Flea".into(),
};

// Convert into a `JsonApiDocument`
let doc = example_flea.to_jsonapi_document();
assert!(doc.is_valid());

// Convert into a `Resource`
let resource = example_flea.to_jsonapi_resource();

Deserializing a JSON:API Document

Deserialize a JSON:API document using serde by explicitly declaring the variable type in Result

use jsonapi_rs::model::Resource;
let serialized = r#"
{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON:API paints my bikeshed!",
      "body": "The shortest article. Ever."
    }
}"#;
let data: Result<Resource, serde_json::Error> = serde_json::from_str(&serialized);
assert_eq!(data.is_ok(), true);

Or parse the String directly using the Resource::from_str trait implementation

use std::str::FromStr;
use jsonapi_rs::model::Resource;
let serialized = r#"
{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON:API paints my bikeshed!",
      "body": "The shortest article. Ever."
    }
}"#;
let data = Resource::from_str(&serialized);
assert_eq!(data.is_ok(), true);

JsonApiDocument implements PartialEq which allows two documents to be compared for equality. If two documents possess the same contents the ordering of the attributes and fields within the JSON:API document are irrelevant and their equality will be true.

Testing

Run the tests:

cargo test

Run tests with more verbose output:

RUST_BACKTRACE=1 cargo test -- --nocapture

Run tests whenever files are modified using cargo watch:

RUST_BACKTRACE=1 cargo watch "test -- --nocapture"

Modules

  • Defines custom types and structs primarily that composite the JSON:API document
  • Defines trait and implementations that allow a has many relationship to be optional
  • Defines the JsonApiModel trait. This is primarily used in conjunction with the jsonapi_model! macro to allow arbitrary structs which implement Deserialize to be converted to/from a JsonApiDocument or Resource

Macros