require 'jsonapi/deserializable'
class ApplicationController < ActionController::API
include JSONAPI::Deserialization
before_action :deserialize_jsonapi_request
private
def deserialize_jsonapi_request
return unless request.content_type == 'application/vnd.api+json'
hash = request.request_parameters
hash = hash.to_unsafe_hash if Rails::VERSION::MAJOR >= 5
ActiveModelSerializers::Deserialization.jsonapi_parse!(hash)
rescue ActiveModelSerializers::Deserialization::InvalidDocument => e
render jsonapi_errors: e.errors, status: :unprocessable_entity
end
end
We require the jsonapi/deserializable library to access the JSONAPI::Deserialization module.
Inside the
ApplicationController
, we include theJSONAPI::Deserialization
module. This mixes in the deserialization functionality into the controller.We define a
before_action
callback that calls thedeserialize_jsonapi_request
method before each action in the controller.In the
deserialize_jsonapi_request
method:4.1 We check if the request's
content_type
isapplication/vnd.api+json
. Ifnot, we skip deserialization.
4.2 We retrieve the request parameters using
request.request_parameters
.4.3 If using Rails 5 or later, we convert the parameters to an unsafe hash
using
to_unsafe_hash
for compatibility.4.4 We call
ActiveModelSerializers::Deserialization.jsonapi_parse!
to parseand deserialize the JSONAPI request parameters.
4.5 If anActiveModelSerializers::Deserialization::InvalidDocument
exceptionis raised during deserialization (indicating invalid JSONAPI input), we
render a JSONAPI error response with a status of
:unprocessable_entity
.With this setup, the
JSONAPI::Deserialization
module will be included in theApplicationController
, and thedeserialize_jsonapi_request
method will be called before each action to deserialize the incoming JSONAPI request parameters.Remember to have the
jsonapi-serializer
gem (or a similar JSONAPI serialization/deserialization library) installed in your application for this code to work.