/jsonapi_parameters

Rails-way to consume JSON:API input

Primary LanguageRubyMIT LicenseMIT

JsonApi::Parameters

Simple JSON:API compliant parameters translator.

Gem Version Maintainability Test Coverage

Documentation

Usage

Installation

Add this line to your application's Gemfile:

gem 'jsonapi_parameters'

And then execute:

$ bundle

Or install it yourself as:

$ gem install jsonapi_parameters

Rails

Usually your strong parameters in controller are invoked this way:

def create
  model = Model.new(create_params)
  
  if model.save
    ...
  else
    head 500
  end
end

private

def create_params
  params.require(:model).permit(:name)
end

With jsonapi_parameters, the difference is just the params:

def create_params
  params.from_jsonapi.require(:model).permit(:name)
end

Relationships

JsonApi::Parameters supports ActiveRecord relationship parameters, including nested attributes.

Relationship parameters are being read from two optional trees:

  • relationships,
  • included

If you provide any related resources in the relationships table, this gem will also look for corresponding, included resources and their attributes. Thanks to that this gem supports nested attributes, and will try to translate these included resources and pass them along.

For more examples take a look at Relationships in the wiki documentation.

Plain Ruby / outside Rails

params = { # JSON:API compliant parameters here
	# ...
}

class Translator
  include JsonApi::Parameters
end
translator = Translator.new

translator.jsonapify(params)

Mime Type

As stated in the JSON:API specification correct mime type for JSON:API input should be application/vnd.api+json.

This gems intention is to make input consumption as easy as possible. Hence, it registers this mime type for you.

Customization

If you need custom relationship handling (for instance, if you have a relationship named scissors that is plural, but it actually is a single entity), you can use Handlers to define appropriate behaviour.

Read more at Relationship Handlers

License

The gem is available as open source under the terms of the MIT License.