jsonapi-crystal

CI Docs License

Framework-agnostic JSON:API v1.1 (application/vnd.api+json) toolkit for Crystal (>= 1.16.0) with zero runtime dependencies.

Pairs cleanly with vite-crystal, vite-plugin-crystal, and static-assets in a single HTTP::Server handler stack.

Features

Installation

Add jsonapi to your shard.yml:

dependencies:
  jsonapi:
    github: spcbeck/jsonapi-crystal
    version: ~> 0.1.0

Run shards install, then require "jsonapi".

Usage

1. Define Resources

require "jsonapi"

class AuthorResource
  include JSONAPI::Resource

  jsonapi_type "people"
  jsonapi_attributes :name, :twitter

  getter id : Int32
  getter name : String
  getter twitter : String?

  def initialize(@id : Int32, @name : String, @twitter : String? = nil)
  end
end

class ArticleResource
  include JSONAPI::Resource

  jsonapi_type "articles"
  jsonapi_attributes :title, :status
  jsonapi_has_one :author

  getter id : Int32
  getter title : String
  getter status : String
  getter author : AuthorResource

  def initialize(@id : Int32, @title : String, @status : String, @author : AuthorResource)
  end
end

2. Query Parsing, Serialization & Errors

query = JSONAPI.parse_query(context.request).validate!(
  allowed_includes: ["author"],
  allowed_sorts: ["title", "created_at"],
  allowed_filters: ["status"],
  allowed_fields: {"articles" => ["title", "status"], "people" => ["name"]},
)

links = JSONAPI::PaginationLinks.build(
  "https://example.com/api/articles",
  page: query.page_number || 1,
  per_page: query.page_size || 20,
  total_count: total_articles,
  query: context.request.query_params,
)

JSONAPI.render(context, articles, query: query, links: links)

Handle errors cleanly with JSONAPI.render_error:

rescue ex : JSONAPI::Error
  JSONAPI.render_error(context, ex)
end

3. Deserializing Requests

private struct ArticleAttrs
  include JSON::Serializable
  getter title : String
  getter status : String?
end

input = JSONAPI.deserialize(context.request.body.not_nil!, expected_type: "articles")
attrs = input.attributes_as(ArticleAttrs)
author_id = input.relationship_id("author")

4. Full-Stack HTTP::Server (Vite + StaticAssets + JSON:API)

require "http/server"
require "jsonapi"
require "static_assets"
require "vite"

server = HTTP::Server.new([
  StaticAssets.handler("public"),
  JSONAPI::MediaTypeHandler.new(prefix: "/api"),
]) do |context|
  case {context.request.method, context.request.path}
  when {"GET", "/api/articles"}
    # render JSON:API v1.1 response
  else
    context.response.content_type = "text/html; charset=utf-8"
    context.response.print(<<-HTML)
      <!doctype html>
      <html>
        <head>#{Vite.tags("src/main.ts")}</head>
        <body><div id="app"></div></body>
      </html>
      HTML
  end
end

License

MIT