Simple JSON:API compliant parameters translator.
Add this line to your application's Gemfile:
gem 'jsonapi_parameters'And then execute:
$ bundleOr install it yourself as:
$ gem install jsonapi_parametersUsually 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)
endWith jsonapi_parameters, the difference is just the params:
def create_params
params.from_jsonapi.require(:model).permit(:name)
endJsonApi::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.
params = { # JSON:API compliant parameters here
# ...
}
class Translator
include JsonApi::Parameters
end
translator = Translator.new
translator.jsonapify(params)As stated in the JSON:API specification correct mime type for JSON:API input should be application/vnd.api+json.
This gem's intention is to make input consumption as easy as possible. Hence, it registers this mime type for you.
In theory, any payload may consist of infinite amount of relationships (and so each relationship may have its own, included, infinite amount of nested relationships). Because of that, it is a potential vector of attack.
For this reason we have introduced a default limit of stack levels that JsonApi::Parameters will go down through while parsing the payloads.
This default limit is 3, and can be overwritten by specifying the custom limit.
class Translator
include JsonApi::Parameters
end
translator = Translator.new
translator.jsonapify(custom_stack_limit: 4)
# OR
translator.stack_limit = 4
translator.jsonapify.(...)def create_params
params.from_jsonapi(custom_stack_limit: 4).require(:user).permit(
entities_attributes: { subentities_attributes: { ... } }
)
end
# OR
def create_params
params.stack_level = 4
params.from_jsonapi.require(:user).permit(entities_attributes: { subentities_attributes: { ... } })
ensure
params.reset_stack_limit!
endIf 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.
Project started by Jasiek Matusz.
Currently, jsonapi_parameters is maintained by Visuality's Open Source Commitee.
The gem is available as open source under the terms of the MIT License.