rjapi 0.0.1

A framework-agnostic JSON:API 1.1 implementation for Rust
Documentation
//! Basic example of using the JSON:API library

use rjapi::{JsonApiResource, JsonApiResponse, Resource};
use serde::Serialize;
use serde_json::json;

// A simple `Post` model
#[derive(Serialize)]
struct Post {
    id: String,
    title: String,
    content: String,
    created_at: String,
}

// Implementation of `JsonApiResource` for the `Post` model
impl JsonApiResource for Post {
    const RESOURCE_TYPE: &'static str = "posts";

    fn id(&self) -> String {
        self.id.clone()
    }

    fn attributes(&self) -> serde_json::Value {
        json!({
            "title": self.title,
            "content": self.content,
            "created_at": self.created_at,
        })
    }
}

fn main() {
    // Create an instance of the `Post` model
    let post = Post {
        id: "1".to_string(),
        title: "Example Post".to_string(),
        content: "This is an example post.".to_string(),
        created_at: "2023-01-01T00:00:00Z".to_string(),
    };

    // Create a JSON:API resource from the `Post` model
    let resource = Resource {
        resource_type: Post::RESOURCE_TYPE.to_string(),
        id: post.id(),
        attributes: Some(post.attributes()),
        relationships: None,
        links: None,
        meta: None,
    };

    // Create a JSON:API response using the builder
    let response = JsonApiResponse::new(resource).build();

    // Print the response
    println!("{}", serde_json::to_string_pretty(&response).unwrap());
}