{"id":13665714,"url":"https://github.com/fotinakis/jsonapi-serializers","last_synced_at":"2025-04-26T08:33:05.155Z","repository":{"id":31738284,"uuid":"35304294","full_name":"fotinakis/jsonapi-serializers","owner":"fotinakis","description":"Pure Ruby readonly serializers for the JSON:API spec.","archived":false,"fork":false,"pushed_at":"2020-05-27T23:45:12.000Z","size":290,"stargazers_count":414,"open_issues_count":30,"forks_count":91,"subscribers_count":11,"default_branch":"master","last_synced_at":"2024-10-31T13:25:36.465Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fotinakis.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-05-08T22:14:47.000Z","updated_at":"2024-09-23T10:50:30.000Z","dependencies_parsed_at":"2022-08-20T23:10:57.520Z","dependency_job_id":null,"html_url":"https://github.com/fotinakis/jsonapi-serializers","commit_stats":null,"previous_names":[],"tags_count":34,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fotinakis%2Fjsonapi-serializers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fotinakis%2Fjsonapi-serializers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fotinakis%2Fjsonapi-serializers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fotinakis%2Fjsonapi-serializers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fotinakis","download_url":"https://codeload.github.com/fotinakis/jsonapi-serializers/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224031926,"owners_count":17244361,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T06:00:48.277Z","updated_at":"2024-11-11T00:31:14.874Z","avatar_url":"https://github.com/fotinakis.png","language":"Ruby","readme":"# JSONAPI::Serializers\n\n[![Build Status](https://travis-ci.org/fotinakis/jsonapi-serializers.svg?branch=master)](https://travis-ci.org/fotinakis/jsonapi-serializers)\n[![Gem Version](https://badge.fury.io/rb/jsonapi-serializers.svg)](http://badge.fury.io/rb/jsonapi-serializers)\n\nJSONAPI::Serializers is a simple library for serializing Ruby objects and their relationships into the [JSON:API format](http://jsonapi.org/format/).\n\nThis library is up-to-date with the finalized v1 JSON API spec.\n\n* [Features](#features)\n* [Installation](#installation)\n* [Usage](#usage)\n  * [Define a serializer](#define-a-serializer)\n  * [Serialize an object](#serialize-an-object)\n  * [Serialize a collection](#serialize-a-collection)\n  * [Null handling](#null-handling)\n  * [Multiple attributes](#multiple-attributes)\n  * [Custom attributes](#custom-attributes)\n  * [More customizations](#more-customizations)\n  * [Base URL](#base-url)\n  * [Root metadata](#root-metadata)\n  * [Root links](#root-links)\n  * [Root errors](#root-errors)\n  * [Root jsonapi object](#root-jsonapi-object)\n  * [Explicit serializer discovery](#explicit-serializer-discovery)\n  * [Namespace serializers](#namespace-serializers)\n  * [Sparse fieldsets](#sparse-fieldsets)\n* [Relationships](#relationships)\n  * [Compound documents and includes](#compound-documents-and-includes)\n  * [Relationship path handling](#relationship-path-handling)\n  * [Control links and data in relationships](#control-links-and-data-in-relationships)\n* [Instrumentation](#instrumentation)\n* [Rails example](#rails-example)\n* [Sinatra example](#sinatra-example)\n* [Unfinished business](#unfinished-business)\n* [Contributing](#contributing)\n\n## Features\n\n* Works with **any Ruby web framework**, including Rails, Sinatra, etc. This is a pure Ruby library.\n* Supports the readonly features of the JSON:API spec.\n  * **Full support for compound documents** (\"side-loading\") and the `include` parameter.\n* Similar interface to ActiveModel::Serializers, should provide an easy migration path.\n* Intentionally unopinionated and simple, allows you to structure your app however you would like and then serialize the objects at the end. Easy to integrate with your existing authorization systems and service objects.\n\nJSONAPI::Serializers was built as an intentionally simple serialization interface. It makes no assumptions about your database structure or routes and it does not provide controllers or any create/update interface to the objects. It is a library, not a framework. You will probably still need to do work to make your API fully compliant with the nuances of the [JSON:API spec](http://jsonapi.org/format/), for things like supporting `/relationships` routes and for supporting write actions like creating or updating objects. If you are looking for a more complete and opinionated framework, see the [jsonapi-resources](https://github.com/cerebris/jsonapi-resources) project.\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'jsonapi-serializers'\n```\n\nOr install directly with `gem install jsonapi-serializers`.\n\n## Usage\n\n### Define a serializer\n\n```ruby\nrequire 'jsonapi-serializers'\n\nclass PostSerializer\n  include JSONAPI::Serializer\n\n  attribute :title\n  attribute :content\nend\n```\n\n### Serialize an object\n\n```ruby\nJSONAPI::Serializer.serialize(post)\n```\n\nReturns a hash:\n```json\n{\n  \"data\": {\n    \"id\": \"1\",\n    \"type\": \"posts\",\n    \"attributes\": {\n      \"title\": \"Hello World\",\n      \"content\": \"Your first post\"\n    },\n    \"links\": {\n      \"self\": \"/posts/1\"\n    }\n  }\n}\n```\n\n### Serialize a collection\n\n```ruby\nJSONAPI::Serializer.serialize(posts, is_collection: true)\n```\n\nReturns:\n\n```json\n{\n  \"data\": [\n    {\n      \"id\": \"1\",\n      \"type\": \"posts\",\n      \"attributes\": {\n        \"title\": \"Hello World\",\n        \"content\": \"Your first post\"\n      },\n      \"links\": {\n        \"self\": \"/posts/1\"\n      }\n    },\n    {\n      \"id\": \"2\",\n      \"type\": \"posts\",\n      \"attributes\": {\n        \"title\": \"Hello World again\",\n        \"content\": \"Your second post\"\n      },\n      \"links\": {\n        \"self\": \"/posts/2\"\n      }\n    }\n  ]\n}\n```\n\nYou must always pass `is_collection: true` when serializing a collection, see [Null handling](#null-handling).\n\n### Null handling\n\n```ruby\nJSONAPI::Serializer.serialize(nil)\n```\n\nReturns:\n```json\n{\n  \"data\": null\n}\n```\n\nAnd serializing an empty collection:\n```ruby\nJSONAPI::Serializer.serialize([], is_collection: true)\n```\n\nReturns:\n```json\n{\n  \"data\": []\n}\n```\n\nNote that the JSON:API spec distinguishes in how null/empty is handled for single objects vs. collections, so you must always provide `is_collection: true` when serializing multiple objects. If you attempt to serialize multiple objects without this flag (or a single object with it on) a `JSONAPI::Serializer::AmbiguousCollectionError` will be raised.\n\n### Multiple attributes\nYou could declare multiple attributes at once:\n\n```ruby\n attributes :title, :body, :contents\n```\n\n### Custom attributes\n\nBy default the serializer looks for the same name of the attribute on the object it is given. You can customize this behavior by providing a block to `attribute`, `has_one`, or `has_many`:\n\n```ruby\n  attribute :content do\n    object.body\n  end\n\n  has_one :comment do\n    Comment.where(post: object).take!\n  end\n\n  has_many :authors do\n    Author.where(post: object)\n  end\n```\n\nThe block is evaluated within the serializer instance, so it has access to the `object` and `context` instance variables.\n\n### More customizations\n\nMany other formatting and customizations are possible by overriding any of the following instance methods on your serializers.\n\n```ruby\n# Override this to customize the JSON:API \"id\" for this object.\n# Always return a string from this method to conform with the JSON:API spec.\ndef id\n  object.slug.to_s\nend\n```\n```ruby\n# Override this to customize the JSON:API \"type\" for this object.\n# By default, the type is the object's class name lowercased, pluralized, and dasherized,\n# per the spec naming recommendations: http://jsonapi.org/recommendations/#naming\n# For example, 'MyApp::LongCommment' will become the 'long-comments' type.\ndef type\n  'long-comments'\nend\n```\n```ruby\n# Override this to customize how attribute names are formatted.\n# By default, attribute names are dasherized per the spec naming recommendations:\n# http://jsonapi.org/recommendations/#naming\ndef format_name(attribute_name)\n  attribute_name.to_s.dasherize\nend\n```\n```ruby\n# The opposite of format_name. Override this if you override format_name.\ndef unformat_name(attribute_name)\n  attribute_name.to_s.underscore\nend\n```\n```ruby\n# Override this to provide resource-object metadata.\n# http://jsonapi.org/format/#document-structure-resource-objects\ndef meta\nend\n```\n```ruby\n# Override this to set a base URL (http://example.com) for all links. No trailing slash.\ndef base_url\n  @base_url\nend\n```\n```ruby\n# Override this to provide a resource-object jsonapi object containing the version in use.\n# http://jsonapi.org/format/#document-jsonapi-object\ndef jsonapi\nend\n```\n```ruby\ndef self_link\n  \"#{base_url}/#{type}/#{id}\"\nend\n```\n```ruby\ndef relationship_self_link(attribute_name)\n  \"#{self_link}/relationships/#{format_name(attribute_name)}\"\nend\n```\n```ruby\ndef relationship_related_link(attribute_name)\n  \"#{self_link}/#{format_name(attribute_name)}\"\nend\n```\n\nIf you override `self_link`, `relationship_self_link`, or `relationship_related_link` to return `nil`, the link will be excluded from the serialized object.\n\n### Base URL\n\nYou can override the `base_url` instance method to set a URL to be used in all links.\n\n```ruby\nclass BaseSerializer\n  include JSONAPI::Serializer\n\n  def base_url\n    'http://example.com'\n  end\nend\n\nclass PostSerializer \u003c BaseSerializer\n  attribute :title\n  attribute :content\n\n  has_one :author\n  has_many :comments\nend\n\nJSONAPI::Serializer.serialize(post)\n```\n\nReturns:\n\n```json\n{\n  \"data\": {\n    \"id\": \"1\",\n    \"type\": \"posts\",\n    \"attributes\": {\n      \"title\": \"Hello World\",\n      \"content\": \"Your first post\"\n    },\n    \"links\": {\n      \"self\": \"http://example.com/posts/1\"\n    },\n    \"relationships\": {\n      \"author\": {\n        \"links\": {\n          \"self\": \"http://example.com/posts/1/relationships/author\",\n          \"related\": \"http://example.com/posts/1/author\"\n        }\n      },\n      \"comments\": {\n        \"links\": {\n          \"self\": \"http://example.com/posts/1/relationships/comments\",\n          \"related\": \"http://example.com/posts/1/comments\"\n        },\n      }\n    }\n  }\n}\n```\n\nAlternatively, you can specify `base_url` as an argument to `serialize` which allows you to build the URL with different subdomains or other logic from the request:\n\n```ruby\nJSONAPI::Serializer.serialize(post, base_url: 'http://example.com')\n```\n\nNote: if you override `self_link` in your serializer and leave out `base_url`, it will not be included.\n\n### Root metadata\n\nYou can pass a `meta` argument to specify top-level metadata:\n\n```ruby\nJSONAPI::Serializer.serialize(post, meta: {copyright: 'Copyright 2015 Example Corp.'})\n```\n\n### Root links\n\nYou can pass a `links` argument to specify top-level links:\n\n```ruby\nJSONAPI::Serializer.serialize(post, links: {self: 'https://example.com/posts'})\n```\n\n### Root errors\n\nYou can use `serialize_errors` method in order to specify top-level errors:\n\n```ruby\nerrors = [{ \"title\": \"Invalid Attribute\", \"detail\": \"First name must contain at least three characters.\" }]\nJSONAPI::Serializer.serialize_errors(errors)\n```\n\nIf you are using Rails models (ActiveModel by default), you can pass in an object's errors:\n\n```ruby\nJSONAPI::Serializer.serialize_errors(user.errors)\n```\n\nA more complete usage example (assumes ActiveModel):\n\n```ruby\nclass Api::V1::ReposController \u003c Api::V1::BaseController\n  def create\n    post = Post.create(post_params)\n    if post.errors\n      render json: JSONAPI::Serializer.serialize_errors(post.errors)\n    else\n      render json: JSONAPI::Serializer.serialize(post)\n    end\n  end\nend\n```\n\n### Root 'jsonapi' object\n\nYou can pass a `jsonapi` argument to specify a [top-level \"jsonapi\" key](http://jsonapi.org/format/#document-jsonapi-object) containing the version of JSON:API in use:\n\n```ruby\nJSONAPI::Serializer.serialize(post, jsonapi: {version: '1.0'})\n```\n\n### Explicit serializer discovery\n\nBy default, jsonapi-serializers assumes that the serializer class for `Namespace::User` is `Namespace::UserSerializer`. You can override this behavior on a per-object basis by implementing the `jsonapi_serializer_class_name` method.\n\n```ruby\nclass User\n  def jsonapi_serializer_class_name\n    'SomeOtherNamespace::CustomUserSerializer'\n  end\nend\n```\n\nNow, when a `User` object is serialized, it will use the `SomeOtherNamespace::CustomUserSerializer`.\n\n### Namespace serializers\n\nAssume you have an API with multiple versions:\n\n```ruby\nmodule Api\n  module V1\n    class PostSerializer\n      include JSONAPI::Serializer\n      attribute :title\n    end\n  end\n  module V2\n    class PostSerializer\n      include JSONAPI::Serializer\n      attribute :name\n    end\n  end\nend\n```\n\nWith the namespace option you can choose which serializer is used.\n\n```ruby\nJSONAPI::Serializer.serialize(post, namespace: Api::V1)\nJSONAPI::Serializer.serialize(post, namespace: Api::V2)\n```\n\nThis option overrides the `jsonapi_serializer_class_name` method.\n\n### Sparse fieldsets\n\nThe JSON:API spec allows to return only [specific fields](http://jsonapi.org/format/#fetching-sparse-fieldsets) from attributes and relationships.\n\nFor example, if you wanted to return only the `title` field and `author` relationship link for `posts`:\n\n```ruby\nfields =\nJSONAPI::Serializer.serialize(post, fields: {posts: [:title]})\n```\n\nSparse fieldsets also affect relationship links. In this case, only the `author` relationship link would be included:\n\n``` ruby\nJSONAPI::Serializer.serialize(post, fields: {posts: [:title, :author]})\n```\n\nSparse fieldsets operate on a per-type basis, so they affect all resources in the response including in compound documents. For example, this will affect both the `posts` type in the primary data and the `users` type in the compound data:\n\n``` ruby\nJSONAPI::Serializer.serialize(\n  post,\n  fields: {posts: ['title', 'author'], users: ['name']},\n  include: 'author',\n)\n```\n\nSparse fieldsets support comma-separated strings (`fields: {posts: 'title,author'}`, arrays of strings (`fields: {posts: ['title', 'author']}`), single symbols (`fields: {posts: :title}`), and arrays of symbols (`fields: {posts: [:title, :author]}`).\n\n## Relationships\n\nYou can easily specify relationships with the `has_one` and `has_many` directives.\n\n```ruby\nclass BaseSerializer\n  include JSONAPI::Serializer\nend\n\nclass PostSerializer \u003c BaseSerializer\n  attribute :title\n  attribute :content\n\n  has_one :author\n  has_many :comments\nend\n\nclass UserSerializer \u003c BaseSerializer\n  attribute :name\nend\n\nclass CommentSerializer \u003c BaseSerializer\n  attribute :content\n\n  has_one :user\nend\n```\n\nNote that when serializing a post, the `author` association will come from the `author` attribute on the `Post` instance, no matter what type it is (in this case it is a `User`). This will work just fine, because JSONAPI::Serializers automatically finds serializer classes by appending `Serializer` to the object's class name. This behavior can be customized.\n\nBecause the full class name is used when discovering serializers, JSONAPI::Serializers works with any custom namespaces you might have, like a Rails Engine or standard Ruby module namespace.\n\n### Compound documents and includes\n\n\u003e To reduce the number of HTTP requests, servers MAY allow responses that include related resources along with the requested primary resources. Such responses are called \"compound documents\".\n\u003e [JSON:API Compound Documents](http://jsonapi.org/format/#document-structure-compound-documents)\n\nJSONAPI::Serializers supports compound documents with a simple `include` parameter.\n\nFor example:\n\n```ruby\nJSONAPI::Serializer.serialize(post, include: ['author', 'comments', 'comments.user'])\n```\n\nReturns:\n\n```json\n{\n  \"data\": {\n    \"id\": \"1\",\n    \"type\": \"posts\",\n    \"attributes\": {\n      \"title\": \"Hello World\",\n      \"content\": \"Your first post\"\n    },\n    \"links\": {\n      \"self\": \"/posts/1\"\n    },\n    \"relationships\": {\n      \"author\": {\n        \"links\": {\n          \"self\": \"/posts/1/relationships/author\",\n          \"related\": \"/posts/1/author\"\n        },\n        \"data\": {\n          \"type\": \"users\",\n          \"id\": \"1\"\n        }\n      },\n      \"comments\": {\n        \"links\": {\n          \"self\": \"/posts/1/relationships/comments\",\n          \"related\": \"/posts/1/comments\"\n        },\n        \"data\": [\n          {\n            \"type\": \"comments\",\n            \"id\": \"1\"\n          }\n        ]\n      }\n    }\n  },\n  \"included\": [\n    {\n      \"id\": \"1\",\n      \"type\": \"users\",\n      \"attributes\": {\n        \"name\": \"Post Author\"\n      },\n      \"links\": {\n        \"self\": \"/users/1\"\n      }\n    },\n    {\n      \"id\": \"1\",\n      \"type\": \"comments\",\n      \"attributes\": {\n        \"content\": \"Have no fear, sers, your king is safe.\"\n      },\n      \"links\": {\n        \"self\": \"/comments/1\"\n      },\n      \"relationships\": {\n        \"user\": {\n          \"links\": {\n            \"self\": \"/comments/1/relationships/user\",\n            \"related\": \"/comments/1/user\"\n          },\n          \"data\": {\n            \"type\": \"users\",\n            \"id\": \"2\"\n          }\n        },\n        \"post\": {\n          \"links\": {\n            \"self\": \"/comments/1/relationships/post\",\n            \"related\": \"/comments/1/post\"\n          }\n        }\n      }\n    },\n    {\n      \"id\": \"2\",\n      \"type\": \"users\",\n      \"attributes\": {\n        \"name\": \"Barristan Selmy\"\n      },\n      \"links\": {\n        \"self\": \"/users/2\"\n      }\n    }\n  ]\n}\n```\n\nNotice a few things:\n* The [primary data](http://jsonapi.org/format/#document-structure-top-level) relationships now include \"linkage\" information for each relationship that was included.\n* The related objects themselves are loaded in the top-level `included` member.\n* The related objects _also_ include \"linkage\" data when a deeper relationship is also present in the compound document. This is a very powerful feature of the JSON:API spec, and allows you to deeply link complicated relationships all in the same document and in a single HTTP response. JSONAPI::Serializers automatically includes the correct linkage data for whatever `include` paths you specify. This conforms to this part of the spec:\n\n  \u003e Note: Full linkage ensures that included resources are related to either the primary data (which could be resource objects or resource identifier objects) or to each other.\n  \u003e [JSON:API Compound Documents](http://jsonapi.org/format/#document-compound-documents)\n\n#### Relationship path handling\n\nThe `include` param also accepts a string of [relationship paths](http://jsonapi.org/format/#fetching-includes), ie. `include: 'author,comments,comments.user'` so you can pass an `?include` query param directly through to the serialize method. Be aware that letting users pass arbitrary relationship paths might introduce security issues depending on your authorization setup, where a user could `include` a relationship they might not be authorized to see directly. Be aware of what you allow API users to include.\n\n### Control `links` and `data` in relationships\n\nThe JSON API spec allows relationships objects to contain `links`, `data`, or both.\n\nBy default, `links` are included in each relationship. You can remove links for a specific relationship by passing `include_links: false` to `has_one` or `has_many`. For example:\n\n```ruby\nhas_many :comments, include_links: false  # Default is include_links: true.\n```\n\nNotice that `links` are now excluded for the `comments` relationship:\n\n```json\n   \"relationships\": {\n     \"author\": {\n       \"links\": {\n         \"self\": \"/posts/1/relationships/author\",\n         \"related\": \"/posts/1/author\"\n       }\n     },\n     \"comments\": {}\n   }\n```\n\nBy default, `data` is excluded in each relationship. You can enable data for a specific relationship by passing `include_data: true` to `has_one` or `has_many`. For example:\n\n```ruby\nhas_one :author, include_data: true  # Default is include_data: false.\n```\n\nNotice that linkage data is now included for the `author` relationship:\n\n```json\n   \"relationships\": {\n     \"author\": {\n       \"links\": {\n         \"self\": \"/posts/1/relationships/author\",\n         \"related\": \"/posts/1/author\"\n       },\n       \"data\": {\n         \"type\": \"users\",\n         \"id\": \"1\"\n       }\n     }\n```\n\n## Instrumentation\n\nUsing [ActiveSupport::Notifications](https://api.rubyonrails.org/classes/ActiveSupport/Notifications.html) you can subscribe to key notifications to better understand the performance of your serialization.\n\nThe following notifications can be subscribed to:\n\n* `render.jsonapi_serializers.serialize_primary` - time spent serializing a single object\n* `render.jsonapi_serializers.find_recursive_relationships` - time spent finding objects to serialize through relationships\n\nThis is an example of how you might subscribe to all events that come from `jsonapi-serializers`.\n\n```ruby\nrequire 'active_support/notifications'\n\nActiveSupport::Notifications.subscribe(/^render\\.jsonapi_serializers\\..*/) do |*args|\n  event = ActiveSupport::Notifications::Event.new(*args)\n\n  puts event.name\n  puts event.time\n  puts event.end\n  puts event.payload\nend\n```\n\n## Rails example\n\n```ruby\n# app/serializers/base_serializer.rb\nclass BaseSerializer\n  include JSONAPI::Serializer\n\n  def self_link\n    \"/api/v1#{super}\"\n  end\nend\n\n# app/serializers/post_serializer.rb\nclass PostSerializer \u003c BaseSerializer\n  attribute :title\n  attribute :content\nend\n\n# app/controllers/api/v1/base_controller.rb\nclass Api::V1::BaseController \u003c ActionController::Base\n  # Convenience methods for serializing models:\n  def serialize_model(model, options = {})\n    options[:is_collection] = false\n    JSONAPI::Serializer.serialize(model, options)\n  end\n\n  def serialize_models(models, options = {})\n    options[:is_collection] = true\n    JSONAPI::Serializer.serialize(models, options)\n  end\nend\n\n# app/controllers/api/v1/posts_controller.rb\nclass Api::V1::ReposController \u003c Api::V1::BaseController\n  def index\n    posts = Post.all\n    render json: serialize_models(posts)\n  end\n\n  def show\n    post = Post.find(params[:id])\n    render json: serialize_model(post)\n  end\nend\n\n# config/initializers/jsonapi_mimetypes.rb\n# Without this mimetype registration, controllers will not automatically parse JSON API params.\n\n# Rails 4\nmodule JSONAPI\n  MIMETYPE = \"application/vnd.api+json\"\nend\nMime::Type.register(JSONAPI::MIMETYPE, :api_json)\nActionDispatch::ParamsParser::DEFAULT_PARSERS[Mime::Type.lookup(JSONAPI::MIMETYPE)] = lambda do |body|\n  JSON.parse(body)\nend\n\n# Rails 5 Option 1: Add another synonym to the json mime type\njson_mime_type_synonyms = %w[\n  text/x-json\n  application/jsonrequest\n  application/vnd.api+json\n]\nMime::Type.register('application/json', :json, json_mime_type_synonyms)\n\n# Rails 5 Option 2: Add a separate mime type\nMime::Type.register('application/vnd.api+json', :api_json)\nActionDispatch::Request.parameter_parsers[:api_json] = -\u003e (body) {\n  JSON.parse(body)\n}\n```\n\n## Sinatra example\n\nHere's an example using [Sinatra](http://www.sinatrarb.com) and\n[Sequel ORM](http://sequel.jeremyevans.net) instead of Rails and ActiveRecord.\nThe important takeaways here are that:\n\n1. The `:tactical_eager_loading` plugin will greatly reduce the number of\n   queries performed when sideloading associated records. You can add this\n   plugin to a single model (as demonstrated here), or globally to all models.\n   For more information, please see the Sequel\n   [documentation](http://sequel.jeremyevans.net/rdoc-plugins/classes/Sequel/Plugins/TacticalEagerLoading.html).\n1. The `:skip_collection_check` option must be set to true in order for\n   JSONAPI::Serializer to be able to serialize a single Sequel::Model instance.\n1. You should call `#all` on your Sequel::Dataset instances before passing them\n   to JSONAPI::Serializer to greatly reduce the number of queries performed.\n\n```ruby\nrequire 'sequel'\nrequire 'sinatra/base'\nrequire 'json'\nrequire 'jsonapi-serializers'\n\nclass Post \u003c Sequel::Model\n  plugin :tactical_eager_loading\n\n  one_to_many :comments\nend\n\nclass Comment \u003c Sequel::Model\n  many_to_one :post\nend\n\nclass BaseSerializer\n  include JSONAPI::Serializer\n\n  def self_link\n    \"/api/v1#{super}\"\n  end\nend\n\nclass PostSerializer \u003c BaseSerializer\n  attributes :title, :content\n\n  has_many :comments\nend\n\nclass CommentSerializer \u003c BaseSerializer\n  attributes :username, :content\n\n  has_one :post\nend\n\nmodule Api\n  class V1 \u003c Sinatra::Base\n    configure do\n      mime_type :api_json, 'application/vnd.api+json'\n\n      set :database, Sequel.connect\n    end\n\n    helpers do\n      def parse_request_body\n        return unless request.body.respond_to?(:size) \u0026\u0026\n          request.body.size \u003e 0\n\n        halt 415 unless request.content_type \u0026\u0026\n          request.content_type[/^[^;]+/] == mime_type(:api_json)\n\n        request.body.rewind\n        JSON.parse(request.body.read, symbolize_names: true)\n      end\n\n      # Convenience methods for serializing models:\n      def serialize_model(model, options = {})\n        options[:is_collection] = false\n        options[:skip_collection_check] = true\n        JSONAPI::Serializer.serialize(model, options)\n      end\n\n      def serialize_models(models, options = {})\n        options[:is_collection] = true\n        JSONAPI::Serializer.serialize(models, options)\n      end\n    end\n\n    before do\n      halt 406 unless request.preferred_type.entry == mime_type(:api_json)\n      @data = parse_request_body\n      content_type :api_json\n    end\n\n    get '/posts' do\n      posts = Post.all\n      serialize_models(posts).to_json\n    end\n\n    get '/posts/:id' do\n      post = Post[params[:id].to_i]\n      not_found if post.nil?\n      serialize_model(post, include: 'comments').to_json\n    end\n  end\nend\n```\n\nSee also: [Sinja](https://github.com/mwpastore/sinja), which extends Sinatra\nand leverages jsonapi-serializers to provide a JSON:API framework.\n\n## Changelog\n\nSee [Releases](https://github.com/fotinakis/jsonapi-serializers/releases).\n\n## Unfinished business\n\n* Support for pagination/sorting is unlikely to be supported because it would likely involve coupling to ActiveRecord, but please open an issue if you have ideas of how to support this generically.\n\n## Contributing\n\n1. Fork it ( https://github.com/fotinakis/jsonapi-serializers/fork )\n2. Create your feature branch (`git checkout -b my-new-feature`)\n3. Commit your changes (`git commit -am 'Add some feature'`)\n4. Push to the branch (`git push origin my-new-feature`)\n5. Create a new Pull Request\n\nThrow a ★ on it! :)\n","funding_links":[],"categories":["1. language"],"sub_categories":["1.1 ruby"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffotinakis%2Fjsonapi-serializers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffotinakis%2Fjsonapi-serializers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffotinakis%2Fjsonapi-serializers/lists"}