jsonapi-crystal v0.1.0

Framework-agnostic JSON:API v1.1 serializer, deserializer, query parser, error builder, and content-negotiation HTTP::Handler for Crystal

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

  • Declarative JSONAPI::Resource DSL: jsonapi_type, jsonapi_id, jsonapi_attributes, custom jsonapi_attribute keys/blocks, jsonapi_has_one, and jsonapi_has_many.
  • Streaming JSON::Builder serializer: Emits JSON:API v1.1 documents (jsonapi: { "version": "1.1" }), compound included documents deduplicated by {type, id}, cycle-safe nested include trees, sparse fieldsets (fields[...]), pagination links, and meta.
  • Typed QueryParams parser & allowlist validator: Parses include, fields[...], sort, filter[...], and page[...] directly from HTTP::Request, raising spec-compliant 400 Bad Request error objects with source.parameter pointers on disallowed inputs.
  • Request Deserializer: Validates incoming JSON:API POST/PATCH bodies (type, id, attributes, relationships) with JSON Pointer source.pointer error reporting (400, 409 Conflict, 422 Unprocessable Content).
  • JSON:API §6.2 MediaTypeHandler: Enforces 415 Unsupported Media Type and 406 Not Acceptable content negotiation (allowing ext and profile parameters per v1.1) and sets Content-Type: application/vnd.api+json.

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

Repository

jsonapi-crystal

Owner
Statistic
  • 0
  • 0
  • 0
  • 0
  • 1
  • about 2 hours ago
  • December 6, 2026
License

MIT License

Links
Synced at

Sun, 06 Dec 2026 08:58:21 GMT

Languages