We'll gladly accept bugfixes and security-related fixes for v2 (the master branch), but at this stage, contributions for new features/improvements are welcome only for v3. Please feel free to leave comments in the v3 Pull Request.
A fast JSON:API serializer for Ruby Objects.
Previously this project was called fast_jsonapi, we forked the project and renamed it to jsonapi/serializer in order to keep it alive.
We would like to thank the Netflix team for the initial work and to all our contributors and users for the continuous support!
We compare serialization times with ActiveModelSerializer and alternative implementations as part of performance tests available at jsonapi-serializer/comparisons.
We want to ensure that with every change on this library, serialization time stays significantly faster than the performance provided by the alternatives. Please read the performance article in the docs folder for any questions related to methodology.
- Features
- Installation
- Usage
- Performance Instrumentation
- Deserialization
- Migrating from Netflix/fast_jsonapi
- Contributing
- Declaration syntax similar to Active Model Serializer
- Support for
belongs_to,has_manyandhas_one - Support for compound documents (included)
- Optimized serialization of compound documents
- Caching
Add this line to your application's Gemfile:
gem'jsonapi-serializer'Execute:
$ bundle installYou can use the bundled generator if you are using the library inside of a Rails project:
rails g serializer Movie name year This will create a new serializer in app/serializers/movie_serializer.rb
classMovieattr_accessor:id,:name,:year,:actor_ids,:owner_id,:movie_type_idendclassMovieSerializerincludeJSONAPI::Serializerset_type:movie# optionalset_id:owner_id# optionalattributes:name,:yearhas_many:actorsbelongs_to:owner,record_type: :userbelongs_to:movie_typeendmovie=Movie.newmovie.id=232movie.name='test movie'movie.actor_ids=[1,2,3]movie.owner_id=3movie.movie_type_id=1moviemovies=2.times.mapdo |i| m=Movie.newm.id=i + 1m.name="test movie #{i}"m.actor_ids=[1,2,3]m.owner_id=3m.movie_type_id=1mendhash=MovieSerializer.new(movie).serializable_hashjson_string=MovieSerializer.new(movie).serializable_hash.to_json{"data":{"id": "3", "type": "movie", "attributes":{"name": "test movie", "year": null }, "relationships":{"actors":{"data": [{"id": "1", "type": "actor" },{"id": "2", "type": "actor" } ] }, "owner":{"data":{"id": "3", "type": "user" } } } } } By default fast_jsonapi will try to figure the type based on the name of the serializer class. For example class MovieSerializer will automatically have a type of :movie. If your serializer class name does not follow this format, you have to manually state the set_type at the serializer.
By 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
classMovieSerializerincludeJSONAPI::Serializer# Available options :camel, :camel_lower, :dash, :underscore(default)set_key_transform:camelendHere are examples of how these options transform the keys
set_key_transform:camel# "some_key" => "SomeKey"set_key_transform:camel_lower# "some_key" => "someKey"set_key_transform:dash# "some_key" => "some-key"set_key_transform:underscore# "some_key" => "some_key"Attributes are defined using the attributes method. This method is also aliased as attribute, which is useful when defining a single attribute.
By 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:
classMovieSerializerincludeJSONAPI::Serializerattribute:nameendCustom attributes that must be serialized but do not exist on the model can be declared using Ruby block syntax:
classMovieSerializerincludeJSONAPI::Serializerattributes:name,:yearattribute:name_with_yeardo |object| "#{object.name} (#{object.year})"endendThe block syntax can also be used to override the property on the object:
classMovieSerializerincludeJSONAPI::Serializerattribute:namedo |object| "#{object.name} Part 2"endendAttributes can also use a different name by passing the original method or accessor with a proc shortcut:
classMovieSerializerincludeJSONAPI::Serializerattributes:nameattribute:released_in_year, &:yearendLinks are defined 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.
You 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.
You 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
classMovieSerializerincludeJSONAPI::Serializerlink:public_urllink:self,:urllink:custom_urldo |object| "https://movies.com/#{object.name}-(#{object.year})"endlink:personalized_urldo |object,params| "https://movies.com/#{object.name}-#{params[:user].reference_code}"endendYou can specify relationship links 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)
classMovieSerializerincludeJSONAPI::Serializerhas_many:actors,links: {self: :url,related: ->(object){"https://movies.com/#{object.id}/actors"}}endRelationship links can also be configured to be defined as a method on the object.
has_many:actors,links: :actor_relationship_linksThis 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:
has_many:actors,lazy_load_data: true,links: {self: :url,related: ->(object){"https://movies.com/#{object.id}/actors"}}For 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.
classMovieSerializerincludeJSONAPI::Serializermetado |movie| {years_since_release: Date.current.year - movie.year}endendYou can specify relationship meta by using the meta: option on the serializer. Relationship meta in JSON API is useful if you wish to provide non-standard meta-information about the relationship.
Meta can be defined either by passing a static hash or by using Proc to the meta key. In the latter case, the record and any params passed to the serializer are available inside the Proc as the first and second parameters, respectively.
classMovieSerializerincludeJSONAPI::Serializerhas_many:actors,meta: Proc.newdo |movie_record,params| {count: movie_record.actors.length}endendSupport for top-level and nested included associations through options[:include].
options={}options[:meta]={total: 2}options[:links]={self: '...',next: '...',prev: '...'}options[:include]=[:actors,:'actors.agency',:'actors.agency.state']MovieSerializer.new(movies,options).serializable_hash.to_jsonoptions[:meta]={total: 2}options[:links]={self: '...',next: '...',prev: '...'}hash=MovieSerializer.new(movies,options).serializable_hashjson_string=MovieSerializer.new(movies,options).serializable_hash.to_jsonYou can use is_collection option to have better control over collection serialization.
If this option is not provided or nil autodetect logic is used to try understand if provided resource is a single object or collection.
Autodetect logic is compatible with most DB toolkits (ActiveRecord, Sequel, etc.) but cannot guarantee that single vs collection will be always detected properly.
options[:is_collection]was introduced to be able to have precise control this behavior
nilor not provided: will try to autodetect single vs collection (please, see notes above)truewill always treat input resource as collectionfalsewill always treat input resource as single object
To enable caching, use cache_options store: <cache_store>:
classMovieSerializerincludeJSONAPI::Serializer# use rails cache with a separate namespace and fixed expirycache_optionsstore: Rails.cache,namespace: 'jsonapi-serializer',expires_in: 1.hourendstore is required can be anything that implements a #fetch(record, **options, &block) method:
recordis the record that is currently serializedoptionsis everything that was passed tocache_optionsexceptstore, so it can be everything the cache store supports&blockshould be executed to fetch new data if cache is empty
So for the example above it will call the cache instance like this:
Rails.cache.fetch(record,namespace: 'jsonapi-serializer',expires_in: 1.hour){ ... }If caching is enabled and fields are provided to the serializer, the fieldset will be appended to the cache key's namespace.
For example, given the following serializer definition and instance:
classActorSerializerincludeJSONAPI::Serializerattributes:first_name,:last_namecache_optionsstore: Rails.cache,namespace: 'jsonapi-serializer',expires_in: 1.hourendserializer=ActorSerializer.new(actor,{fields: {actor: [:first_name]}})The following cache namespace will be generated: 'jsonapi-serializer-fieldset:first_name'.
In some cases, attribute values might require more information than what is available on the record, for example, access privileges or other information related to a current authenticated user. The options[:params] value covers these cases by allowing you to pass in a hash of additional parameters necessary for your use case.
Leveraging the new params is easy, when you define a custom id, attribute or relationship with a block you opt-in to using params by adding it as a block parameter.
classMovieSerializerincludeJSONAPI::Serializerset_iddo |movie,params| # in here, params is a hash containing the `:admin` keyparams[:admin] ? movie.owner_id : "movie-#{movie.id}"endattributes:name,:yearattribute:can_view_earlydo |movie,params| # in here, params is a hash containing the `:current_user` keyparams[:current_user].is_employee? ? true : falseendbelongs_to:primary_agentdo |movie,params| # in here, params is a hash containing the `:current_user` keyparams[:current_user]endend# ...current_user=User.find(cookies[:current_user_id])serializer=MovieSerializer.new(movie,{params: {current_user: current_user}})serializer.serializable_hashCustom attributes and relationships that only receive the resource are still possible by defining the block to only receive one argument.
Conditional 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.
classMovieSerializerincludeJSONAPI::Serializerattributes:name,:yearattribute:release_year,if: Proc.new{ |record| # Release year will only be serialized if it's greater than 1990record.release_year > 1990}attribute:director,if: Proc.new{ |record,params| # The director will be serialized only if the :admin key of params is trueparams && params[:admin] == true}# Custom attribute `name_year` will only be serialized if both `name` and `year` fields are presentattribute:name_year,if: Proc.new{ |record| record.name.present? && record.year.present?}do |object| "#{object.name} - #{object.year}"endend# ...current_user=User.find(cookies[:current_user_id])serializer=MovieSerializer.new(movie,{params: {admin: current_user.admin?}})serializer.serializable_hashConditional 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.
classMovieSerializerincludeJSONAPI::Serializer# Actors will only be serialized if the record has any associated actorshas_many:actors,if: Proc.new{ |record| record.actors.any?}# Owner will only be serialized if the :admin key of params is truebelongs_to:owner,if: Proc.new{ |record,params| params && params[:admin] == true}end# ...current_user=User.find(cookies[:current_user_id])serializer=MovieSerializer.new(movie,{params: {admin: current_user.admin?}})serializer.serializable_hashIn many cases, the relationship can automatically detect the serializer to use.
classMovieSerializerincludeJSONAPI::Serializer# resolves to StudioSerializerbelongs_to:studio# resolves to ActorSerializerhas_many:actorsendAt other times, such as when a property name differs from the class name, you may need to explicitly state the serializer to use. You can do so by specifying a different symbol or the serializer class itself (which is the recommended usage):
classMovieSerializerincludeJSONAPI::Serializer# resolves to MovieStudioSerializerbelongs_to:studio,serializer: :movie_studio# resolves to PerformerSerializerhas_many:actors,serializer: PerformerSerializerendFor more advanced cases, such as polymorphic relationships and Single Table Inheritance, you may need even greater control to select the serializer based on the specific object or some specified serialization parameters. You can do by defining the serializer as a Proc:
classMovieSerializerincludeJSONAPI::Serializerhas_many:actors,serializer: Proc.newdo |record,params| ifrecord.comedian?ComedianSerializerelsifparams[:use_drama_serializer]DramaSerializerelseActorSerializerendendendYou can order the has_many relationship by providing a block:
classMovieSerializerincludeJSONAPI::Serializerhas_many:actorsdo |movie| movie.actors.order(position: :asc)endendAttributes and relationships can be selectively returned per record type by using the fields option.
classMovieSerializerincludeJSONAPI::Serializerattributes:name,:yearendserializer=MovieSerializer.new(movie,{fields: {movie: [:name]}})serializer.serializable_hashYou can mix-in code from another ruby module into your serializer class to reuse functions across your app.
Since 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.
moduleAvatarHelperextendActiveSupport::Concernclass_methodsdodefavatar_url(user)user.image.urlendendendclassUserSerializerincludeJSONAPI::SerializerincludeAvatarHelper# mixes in your helper method as class methodset_type:userattributes:name,:emailattribute:avatardo |user| avatar_url(user)endendmoduleAvatarHelperdefavatar_url(user)user.image.urlendendclassUserSerializerincludeJSONAPI::SerializerextendAvatarHelper# mixes in your helper method as class methodset_type:userattributes:name,:emailattribute:avatardo |user| avatar_url(user)endend| Option | Purpose | Example |
|---|---|---|
| set_type | Type name of Object | set_type :movie |
| key | Key of Object | belongs_to :owner, key: :user |
| set_id | ID of Object | set_id :owner_id or set_id{|record, params| params[:admin] ? record.id : "#{record.name.downcase}-#{record.id}" } |
| cache_options | Hash with store to enable caching and optional further cache options | cache_options store: ActiveSupport::Cache::MemoryStore.new, expires_in: 5.minutes |
| id_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 |
| object_method_name | Set custom method name to get related objects | has_many :locations, object_method_name: :places |
| record_type | Set custom Object Type for a relationship | belongs_to :owner, record_type: :user |
| serializer | Set custom Serializer for a relationship | has_many :actors, serializer: :custom_actor, has_many :actors, serializer: MyApp::Api::V1::ActorSerializer, or has_many :actors, serializer -> (object, params){(return a serializer class) } |
| polymorphic | Allows different record types for a polymorphic association | has_many :targets, polymorphic: true |
| polymorphic | Sets custom record types for each object class in a polymorphic association | has_many :targets, polymorphic:{Person => :person, Group => :group } |
Performance instrumentation is available by using the active_support/notifications.
To enable it, include the module in your serializer class:
require'jsonapi/serializer'require'jsonapi/serializer/instrumentation'classMovieSerializerincludeJSONAPI::SerializerincludeJSONAPI::Serializer::Instrumentation# ...endSkylight integration is also available and supported by us, follow the Skylight documentation to enable it.
The project has and requires unit tests, functional tests and performance tests. To run tests use the following command:
rspecWe currently do not support deserialization, but we recommend to use any of the next gems:
This gem provides the next features alongside deserialization:
- Collection meta
- Error handling
- Includes and sparse fields
- Filtering and sorting
- Pagination
If you come from Netflix/fast_jsonapi, here is the instructions to switch.
- gem 'fast_jsonapi'+ gem 'jsonapi-serializer'class MovieSerializer - include FastJsonapi::ObjectSerializer+ include JSONAPI::Serializer end- json_string = MovieSerializer.new(movie).serialized_json+ json_string = MovieSerializer.new(movie).serializable_hash.to_json- require 'fast_jsonapi'+ require 'jsonapi/serializer'See docs.
- cache_options enabled: true, cache_length: 12.hours+ cache_options store: Rails.cache, namespace: 'jsonapi-serializer', expires_in: 1.hourPlease follow the instructions we provide as part of the issue and pull request creation processes.
This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.