{"id":13482777,"url":"https://github.com/Netflix/fast_jsonapi","last_synced_at":"2025-03-27T13:32:38.230Z","repository":{"id":41321990,"uuid":"119760423","full_name":"Netflix/fast_jsonapi","owner":"Netflix","description":"No Longer Maintained - A lightning fast JSON:API serializer for Ruby Objects.","archived":false,"fork":false,"pushed_at":"2023-03-06T16:52:00.000Z","size":336,"stargazers_count":5069,"open_issues_count":106,"forks_count":425,"subscribers_count":391,"default_branch":"master","last_synced_at":"2024-10-29T11:13:35.454Z","etag":null,"topics":["not-maintained"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Netflix.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2018-02-01T00:19:19.000Z","updated_at":"2024-10-26T11:06:02.000Z","dependencies_parsed_at":"2022-08-10T01:54:16.721Z","dependency_job_id":"683a83ad-d3d7-4fd3-9b6a-d8740c632723","html_url":"https://github.com/Netflix/fast_jsonapi","commit_stats":{"total_commits":231,"total_committers":72,"mean_commits":"3.2083333333333335","dds":0.9177489177489178,"last_synced_commit":"68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7"},"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Netflix%2Ffast_jsonapi","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Netflix%2Ffast_jsonapi/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Netflix%2Ffast_jsonapi/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Netflix%2Ffast_jsonapi/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Netflix","download_url":"https://codeload.github.com/Netflix/fast_jsonapi/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245535501,"owners_count":20631297,"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":["not-maintained"],"created_at":"2024-07-31T17:01:05.433Z","updated_at":"2025-03-27T13:32:38.199Z","avatar_url":"https://github.com/Netflix.png","language":"Ruby","readme":"# Fast JSON API — :warning: This project is no longer maintained!!!! :warning:\n\n[![Build Status](https://travis-ci.org/Netflix/fast_jsonapi.svg?branch=master)](https://travis-ci.org/Netflix/fast_jsonapi)\n\nA lightning fast [JSON:API](http://jsonapi.org/) serializer for Ruby Objects.\n\n### Since this project is no longer maintained, please consider using alternatives or the forked project [jsonapi-serializer/jsonapi-serializer](https://github.com/jsonapi-serializer/jsonapi-serializer)!\n\n# Performance Comparison\n\nWe compare serialization times with Active Model Serializer as part of RSpec performance tests included on this library. We want to ensure that with every change on this library, serialization time is at least `25 times` faster than Active Model Serializers on up to current benchmark of 1000 records. Please read the [performance document](https://github.com/Netflix/fast_jsonapi/blob/master/performance_methodology.md) for any questions related to methodology.\n\n## Benchmark times for 250 records\n\n```bash\n$ rspec\nActive Model Serializer serialized 250 records in 138.71 ms\nFast JSON API serialized 250 records in 3.01 ms\n```\n\n# Table of Contents\n\n* [Features](#features)\n* [Installation](#installation)\n* [Usage](#usage)\n  * [Rails Generator](#rails-generator)\n  * [Model Definition](#model-definition)\n  * [Serializer Definition](#serializer-definition)\n  * [Object Serialization](#object-serialization)\n  * [Compound Document](#compound-document)\n  * [Key Transforms](#key-transforms)\n  * [Collection Serialization](#collection-serialization)\n  * [Caching](#caching)\n  * [Params](#params)\n  * [Conditional Attributes](#conditional-attributes)\n  * [Conditional Relationships](#conditional-relationships)\n  * [Sparse Fieldsets](#sparse-fieldsets)\n  * [Using helper methods](#using-helper-methods)\n* [Contributing](#contributing)\n\n\n## Features\n\n* Declaration syntax similar to Active Model Serializer\n* Support for `belongs_to`, `has_many` and `has_one`\n* Support for compound documents (included)\n* Optimized serialization of compound documents\n* Caching\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'fast_jsonapi'\n```\n\nExecute:\n\n```bash\n$ bundle install\n```\n\n## Usage\n\n### Rails Generator\nYou can use the bundled generator if you are using the library inside of\na Rails project:\n\n    rails g serializer Movie name year\n\nThis will create a new serializer in `app/serializers/movie_serializer.rb`\n\n### Model Definition\n\n```ruby\nclass Movie\n  attr_accessor :id, :name, :year, :actor_ids, :owner_id, :movie_type_id\nend\n```\n\n### Serializer Definition\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n  set_type :movie  # optional\n  set_id :owner_id # optional\n  attributes :name, :year\n  has_many :actors\n  belongs_to :owner, record_type: :user\n  belongs_to :movie_type\nend\n```\n\n### Sample Object\n\n```ruby\nmovie = Movie.new\nmovie.id = 232\nmovie.name = 'test movie'\nmovie.actor_ids = [1, 2, 3]\nmovie.owner_id = 3\nmovie.movie_type_id = 1\nmovie\n```\n\n### Object Serialization\n\n#### Return a hash\n```ruby\nhash = MovieSerializer.new(movie).serializable_hash\n```\n\n#### Return Serialized JSON\n```ruby\njson_string = MovieSerializer.new(movie).serialized_json\n```\n\n#### Serialized Output\n\n```json\n{\n  \"data\": {\n    \"id\": \"3\",\n    \"type\": \"movie\",\n    \"attributes\": {\n      \"name\": \"test movie\",\n      \"year\": null\n    },\n    \"relationships\": {\n      \"actors\": {\n        \"data\": [\n          {\n            \"id\": \"1\",\n            \"type\": \"actor\"\n          },\n          {\n            \"id\": \"2\",\n            \"type\": \"actor\"\n          }\n        ]\n      },\n      \"owner\": {\n        \"data\": {\n          \"id\": \"3\",\n          \"type\": \"user\"\n        }\n      }\n    }\n  }\n}\n\n```\n\n### Key Transforms\nBy default fast_jsonapi underscores the key names. It supports the same key transforms that are supported by AMS. Here is the syntax of specifying a key transform\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n  # Available options :camel, :camel_lower, :dash, :underscore(default)\n  set_key_transform :camel\nend\n```\nHere are examples of how these options transform the keys\n\n```ruby\nset_key_transform :camel # \"some_key\" =\u003e \"SomeKey\"\nset_key_transform :camel_lower # \"some_key\" =\u003e \"someKey\"\nset_key_transform :dash # \"some_key\" =\u003e \"some-key\"\nset_key_transform :underscore # \"some_key\" =\u003e \"some_key\"\n```\n\n### Attributes\nAttributes are defined in FastJsonapi using the `attributes` method.  This method is also aliased as `attribute`, which is useful when defining a single attribute.\n\nBy default, attributes are read directly from the model property of the same name.  In this example, `name` is expected to be a property of the object being serialized:\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n\n  attribute :name\nend\n```\n\nCustom attributes that must be serialized but do not exist on the model can be declared using Ruby block syntax:\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n\n  attributes :name, :year\n\n  attribute :name_with_year do |object|\n    \"#{object.name} (#{object.year})\"\n  end\nend\n```\n\nThe block syntax can also be used to override the property on the object:\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n\n  attribute :name do |object|\n    \"#{object.name} Part 2\"\n  end\nend\n```\n\nAttributes can also use a different name by passing the original method or accessor with a proc shortcut:\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n\n  attributes :name\n\n  attribute :released_in_year, \u0026:year\nend\n```\n\n### Links Per Object\nLinks are defined in FastJsonapi using the `link` method. By default, links are read directly from the model property of the same name. In this example, `public_url` is expected to be a property of the object being serialized.\n\nYou can configure the method to use on the object for example a link with key `self` will get set to the value returned by a method called `url` on the movie object.\n\nYou can also use a block to define a url as shown in `custom_url`. You can access params in these blocks as well as shown in `personalized_url`\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n\n  link :public_url\n\n  link :self, :url\n\n  link :custom_url do |object|\n    \"http://movies.com/#{object.name}-(#{object.year})\"\n  end\n\n  link :personalized_url do |object, params|\n    \"http://movies.com/#{object.name}-#{params[:user].reference_code}\"\n  end\nend\n```\n\n#### Links on a Relationship\n\nYou can specify [relationship links](http://jsonapi.org/format/#document-resource-object-relationships) by using the `links:` option on the serializer. Relationship links in JSON API are useful if you want to load a parent document and then load associated documents later due to size constraints (see [related resource links](http://jsonapi.org/format/#document-resource-object-related-resource-links))\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n\n  has_many :actors, links: {\n    self: :url,\n    related: -\u003e (object) {\n      \"https://movies.com/#{object.id}/actors\"\n    }\n  }\nend\n```\n\nThis will create a `self` reference for the relationship, and a `related` link for loading the actors relationship later. NB: This will not automatically disable loading the data in the relationship, you'll need to do that using the `lazy_load_data` option:\n\n```ruby\n  has_many :actors, lazy_load_data: true, links: {\n    self: :url,\n    related: -\u003e (object) {\n      \"https://movies.com/#{object.id}/actors\"\n    }\n  }\n```\n\n### Meta Per Resource\n\nFor every resource in the collection, you can include a meta object containing non-standard meta-information about a resource that can not be represented as an attribute or relationship.\n\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n\n  meta do |movie|\n    {\n      years_since_release: Date.current.year - movie.year\n    }\n  end\nend\n```\n\n### Compound Document\n\nSupport for top-level and nested included associations through ` options[:include] `.\n\n```ruby\noptions = {}\noptions[:meta] = { total: 2 }\noptions[:links] = {\n  self: '...',\n  next: '...',\n  prev: '...'\n}\noptions[:include] = [:actors, :'actors.agency', :'actors.agency.state']\nMovieSerializer.new([movie, movie], options).serialized_json\n```\n\n### Collection Serialization\n\n```ruby\noptions[:meta] = { total: 2 }\noptions[:links] = {\n  self: '...',\n  next: '...',\n  prev: '...'\n}\nhash = MovieSerializer.new([movie, movie], options).serializable_hash\njson_string = MovieSerializer.new([movie, movie], options).serialized_json\n```\n\n#### Control Over Collection Serialization\n\nYou can use `is_collection` option to have better control over collection serialization.\n\nIf this option is not provided or `nil` autedetect logic is used to try understand\nif provided resource is a single object or collection.\n\nAutodetect logic is compatible with most DB toolkits (ActiveRecord, Sequel, etc.) but\n**cannot** guarantee that single vs collection will be always detected properly.\n\n```ruby\noptions[:is_collection]\n```\n\nwas introduced to be able to have precise control this behavior\n\n- `nil` or not provided: will try to autodetect single vs collection (please, see notes above)\n- `true` will always treat input resource as *collection*\n- `false` will always treat input resource as *single object*\n\n### Caching\nRequires a `cache_key` method be defined on model:\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n  set_type :movie  # optional\n  cache_options enabled: true, cache_length: 12.hours\n  attributes :name, :year\nend\n```\n\n### Params\n\nIn some cases, attribute values might require more information than what is\navailable on the record, for example, access privileges or other information\nrelated to a current authenticated user. The `options[:params]` value covers these\ncases by allowing you to pass in a hash of additional parameters necessary for\nyour use case.\n\nLeveraging the new params is easy, when you define a custom attribute or relationship with a\nblock you opt-in to using params by adding it as a block parameter.\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n\n  attributes :name, :year\n  attribute :can_view_early do |movie, params|\n    # in here, params is a hash containing the `:current_user` key\n    params[:current_user].is_employee? ? true : false\n  end\n\n  belongs_to :primary_agent do |movie, params|\n    # in here, params is a hash containing the `:current_user` key\n    params[:current_user].is_employee? ? true : false\n  end\nend\n\n# ...\ncurrent_user = User.find(cookies[:current_user_id])\nserializer = MovieSerializer.new(movie, {params: {current_user: current_user}})\nserializer.serializable_hash\n```\n\nCustom attributes and relationships that only receive the resource are still possible by defining\nthe block to only receive one argument.\n\n### Conditional Attributes\n\nConditional attributes can be defined by passing a Proc to the `if` key on the `attribute` method. Return `true` if the attribute should be serialized, and `false` if not. The record and any params passed to the serializer are available inside the Proc as the first and second parameters, respectively.\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n\n  attributes :name, :year\n  attribute :release_year, if: Proc.new { |record|\n    # Release year will only be serialized if it's greater than 1990\n    record.release_year \u003e 1990\n  }\n\n  attribute :director, if: Proc.new { |record, params|\n    # The director will be serialized only if the :admin key of params is true\n    params \u0026\u0026 params[:admin] == true\n  }\nend\n\n# ...\ncurrent_user = User.find(cookies[:current_user_id])\nserializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }})\nserializer.serializable_hash\n```\n\n### Conditional Relationships\n\nConditional relationships can be defined by passing a Proc to the `if` key. Return `true` if the relationship should be serialized, and `false` if not. The record and any params passed to the serializer are available inside the Proc as the first and second parameters, respectively.\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n\n  # Actors will only be serialized if the record has any associated actors\n  has_many :actors, if: Proc.new { |record| record.actors.any? }\n\n  # Owner will only be serialized if the :admin key of params is true\n  belongs_to :owner, if: Proc.new { |record, params| params \u0026\u0026 params[:admin] == true }\nend\n\n# ...\ncurrent_user = User.find(cookies[:current_user_id])\nserializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }})\nserializer.serializable_hash\n```\n\n### Sparse Fieldsets\n\nAttributes and relationships can be selectively returned per record type by using the `fields` option.\n\n```ruby\nclass MovieSerializer\n  include FastJsonapi::ObjectSerializer\n\n  attributes :name, :year\nend\n\nserializer = MovieSerializer.new(movie, { fields: { movie: [:name] } })\nserializer.serializable_hash\n```\n\n### Using helper methods\n\nYou can mix-in code from another ruby module into your serializer class to reuse functions across your app.\n\nSince a serializer is evaluated in a the context of a `class` rather than an `instance` of a class, you need to make sure that your methods act as `class` methods when mixed in.\n\n\n##### Using ActiveSupport::Concern\n\n``` ruby\n\nmodule AvatarHelper\n  extend ActiveSupport::Concern\n\n  class_methods do\n    def avatar_url(user)\n      user.image.url\n    end\n  end\nend\n\nclass UserSerializer\n  include FastJsonapi::ObjectSerializer\n\n  include AvatarHelper # mixes in your helper method as class method\n\n  set_type :user\n\n  attributes :name, :email\n\n  attribute :avatar do |user|\n    avatar_url(user)\n  end\nend\n\n```\n\n##### Using Plain Old Ruby\n\n``` ruby\nmodule AvatarHelper\n  def avatar_url(user)\n    user.image.url\n  end\nend\n\nclass UserSerializer\n  include FastJsonapi::ObjectSerializer\n\n  extend AvatarHelper # mixes in your helper method as class method\n\n  set_type :user\n\n  attributes :name, :email\n\n  attribute :avatar do |user|\n    avatar_url(user)\n  end\nend\n\n```\n\n### Customizable Options\n\nOption | Purpose | Example\n------------ | ------------- | -------------\nset_type | Type name of Object | ```set_type :movie ```\nkey | Key of Object | ```belongs_to :owner, key: :user ```\nset_id | ID of Object | ```set_id :owner_id ``` or ```set_id { |record| \"#{record.name.downcase}-#{record.id}\" }```\ncache_options | Hash to enable caching and set cache length | ```cache_options enabled: true, cache_length: 12.hours, race_condition_ttl: 10.seconds```\nid_method_name | Set custom method name to get ID of an object (If block is provided for the relationship, `id_method_name` is invoked on the return value of the block instead of the resource object) | ```has_many :locations, id_method_name: :place_ids ```\nobject_method_name | Set custom method name to get related objects | ```has_many :locations, object_method_name: :places ```\nrecord_type | Set custom Object Type for a relationship | ```belongs_to :owner, record_type: :user```\nserializer | Set custom Serializer for a relationship | ```has_many :actors, serializer: :custom_actor``` or ```has_many :actors, serializer: MyApp::Api::V1::ActorSerializer```\npolymorphic | Allows different record types for a polymorphic association | ```has_many :targets, polymorphic: true```\npolymorphic | Sets custom record types for each object class in a polymorphic association | ```has_many :targets, polymorphic: { Person =\u003e :person, Group =\u003e :group }```\n\n### Instrumentation\n\n`fast_jsonapi` also has builtin [Skylight](https://www.skylight.io/) integration. To enable, add the following to an initializer:\n\n```ruby\nrequire 'fast_jsonapi/instrumentation/skylight'\n```\n\nSkylight relies on `ActiveSupport::Notifications` to track these two core methods. If you would like to use these notifications without using Skylight, simply require the instrumentation integration:\n\n```ruby\nrequire 'fast_jsonapi/instrumentation'\n```\n\nThe two instrumented notifcations are supplied by these two constants:\n* `FastJsonapi::ObjectSerializer::SERIALIZABLE_HASH_NOTIFICATION`\n* `FastJsonapi::ObjectSerializer::SERIALIZED_JSON_NOTIFICATION`\n\nIt is also possible to instrument one method without the other by using one of the following require statements:\n\n```ruby\nrequire 'fast_jsonapi/instrumentation/serializable_hash'\nrequire 'fast_jsonapi/instrumentation/serialized_json'\n```\n\nSame goes for the Skylight integration:\n```ruby\nrequire 'fast_jsonapi/instrumentation/skylight/normalizers/serializable_hash'\nrequire 'fast_jsonapi/instrumentation/skylight/normalizers/serialized_json'\n```\n\n## Contributing\nPlease see [contribution check](https://github.com/Netflix/fast_jsonapi/blob/master/CONTRIBUTING.md) for more details on contributing\n\n### Running Tests\nWe use [RSpec](http://rspec.info/) for testing. We have unit tests, functional tests and performance tests. To run tests use the following command:\n\n```bash\nrspec\n```\n\nTo run tests without the performance tests (for quicker test runs):\n\n```bash\nrspec spec --tag ~performance:true\n```\n\nTo run tests only performance tests:\n\n```bash\nrspec spec --tag performance:true\n```\n","funding_links":[],"categories":["Uncategorized","Ruby","API Builder and Discovery"],"sub_categories":["Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FNetflix%2Ffast_jsonapi","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FNetflix%2Ffast_jsonapi","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FNetflix%2Ffast_jsonapi/lists"}