Start by adding the following to your Gemfile
:
gem 'jsonapi-rails'
Then, once your serializable resources are defined, building
a JSON API document from your business objects is straightforward: simply pass them
to the render
method.
For a comprehensive list of renderer options, see Renderer options.
class PostsController < ActionController::Base
# ...
def index
render jsonapi: Posts.all, include: [:author, comments: [:author]],
fields: { users: [:name, :email],
posts: [:title, :content] }
end
# ...
end
class PostsController < ActionController::Base
# ...
def comments_relationship
post = Post.find(id: params[:id])
render jsonapi: post, relationship: :comments,
include: [comments: [:author]],
fields: { users: [:name, :email],
posts: [:title, :content] }
end
# ...
end
class PostsController < ActionController::Base
# ...
def create
post = Post.new(params[:post])
if post.save
render jsonapi: post
else
render jsonapi_errors: post.errors
end
end
# ...
end
You can customize default behaviors in an initializer ($ rails generate jsonapi:initializer
).
It is also possible to override application-wide settings at controller level. Simply define
one of the available hooks:
jsonapi_class
, jsonapi_errors_class
,jsonapi_object
, jsonapi_include
,
jsonapi_fields
, jsonapi_expose
, jsonapi_pagination
.
It is always possible to override the application/controller-wide settings at action level by providing the relevant renderer options.
By default, for an instance of Article
, the corresponding serializable resource class
will be guessed as SerializableArticle
.
This behavior is customizable by overriding the jsonapi_class
setting (or by supplying
a class
renderer option). Either set it to an explicit hash, or a hash with a dynamic
default value for inferrence.
TODO