This gem gives a few convenient methods for working with JSONAPI. It is inspired by the responders gem.
Add this line to your application's Gemfile:
gem 'json_api_responders'
And then execute:
$ bundle
Inside your base controller, include the module:
module Api
module V1
class BaseController < ApplicationController
include JsonApiResponders
end
end
end
This gem comes with the two following methods respond_with
and respond_with_error
.
This method requires a resource as a parameter, and you can pass some options if you wish. Any options you do choose to pass into respond_with
will be passed on to the controller.render
method. In the Configuration section you can learn how to set mandatory options. Bellow you will find a few examples on how to use this method:
user = User.first
respond_with user
The above example will render the User object.
user = User.first
respond_with user, on_error: {
: :unauthorized, detail: 'Invalid user or password' }
The above example will render an Error response if an error would occur.
This method requires HTTP status code and an optional parameter explaining the error. This method will render an error message as described in the JSON API specification. Below you can see an example of how it should be used:
respond_with_error(401, 'Bad credentials')
respond_with_error(404, 'Not found')
respond_with_error(400, 'Bad request')
Currently you can only configure which options are required to be passed through the respond_with
method. These required options are categorized by the controller's actions. Bellow you can find an example:
# config/initializers/json_api_responders.rb
JsonApiResponders.configure do |config|
config.required_options = {
index: [:each_serializer],
create: [:serializer]
}
end
# app/controllers/v1/users_controller.rb
def create
user = User.create(...)
respond_with user, serializer: UserSerializer
end
If :serializer
was left out of the above respond_with
method you would see the JsonApiResponders::Errors::RequiredOptionMissingError
be raised.
render json: resource, status: 200
render json: resource, status: 200
if resource.valid?
render json: resource, status: 201
else
render error: errors, status: 409
end
if resource.valid?
render json: resource, status: 200
else
render error: errors, status: 409
end
head status: 204
json_api_responders
has translation support for error title and details. Copy & paste this file to your config/locales
folder:
en:
json_api:
errors:
not_found:
title: Not found
detail: Resource not found
forbidden:
title: Unauthorized
detail: User is not authorized to use this resource
unprocessable_entity:
title: Unprocessable Entity
details: Cannot process request
conflict:
title: Invalid Attribute
details: Something is missing
It translates using the format I18n.t("json_api.errors.#{human_readable_status_code}.title")
Bug reports and pull requests are welcome on GitHub at https://github.com/infinum/json_api_responders.