0.04
Low commit activity in last 3 years
No release in over a year
Provides a Formatter for the Grape API DSL to emit objects serialized with jsonapi-serializer.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 4.2.0
~> 3.7

Runtime

 Project Readme

CircleCI

Grape::Jsonapi

Use jsonapi-serializer with Grape.

Installation

Add grape-jsonapi to your Gemfile.

gem 'grape-jsonapi', require: "grape_jsonapi"

Usage

Tell your API to use Grape::Formatter::Jsonapi

class API < Grape::API
  content_type :jsonapi, "application/vnd.api+json"
  formatter :json, Grape::Formatter::Jsonapi
  formatter :jsonapi, Grape::Formatter::Jsonapi
end

Use render to specify JSONAPI options

get "/" do
  user = User.find("123")
  render user, include: [:account]
end

Use a custom serializer

get "/" do
  user = User.find("123")
  render user, serializer: 'CustomUserSerializer'
end

Or

get "/" do
  user = User.find("123")
  render CustomUserSerializer.new(user).serialized_json
end

Override metaand links properties

meta and links properties are usually defined per resource within your serializer (here and here)

However, if you need to override those properties, you can pass them as options when rendering your response:

user = User.find("123")
render user, meta: { pagination: { page: 1, total: 42 } }, links: { self: 'https://my-awesome.app.com/users/1' }

Model parser for response documentation

When using Grape with Swagger via grape-swagger, you can generate response documentation automatically via the provided following model parser:

# FastJsonapi serializer example

# app/serializers/base_serializer.rb
class BaseSerializer; end
# app/serializers/user_serializer.rb
class UserSerializer < BaseSerializer
  include JSONAPI::Serializer

  set_type :user
  has_many :orders

  attributes :name, :email
end

# config/initializers/grape_swagger.rb
GrapeSwagger.model_parsers.register(GrapeSwagger::Jsonapi::Parser, BaseSerializer)

# Your grape API endpoint
desc 'Get current user' do
  success code: 200, model: UserSerializer, message: 'The current user'
# [...]
end

Note that you need the grape-swagger gem for this to work, otherwise it will throw an error.

Credit

Code adapted from grape-jsonapi-resources