Skip to content

prograils/grape_fast_jsonapi

 
 

Repository files navigation

CircleCI

Grape::FastJsonapi

Use fast_jsonapi with Grape.

Installation

Add the grape and grape_fast_jsonapi gems to Gemfile.

gem 'grape'
gem 'grape_fast_jsonapi'

Usage

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

class API < Grape::API
  content_type :jsonapi, "application/vnd.api+json"
  formatter :json, Grape::Formatter::FastJsonapi
  formatter :jsonapi, Grape::Formatter::FastJsonapi
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

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 FastJsonapi::ObjectSerializer

  set_type :user
  has_many :orders

  attributes :name, :email
end

# config/initializers/grape_swagger.rb
GrapeSwagger.model_parsers.register(GrapeSwagger::FastJsonapi::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

About

Use fast_jsonapi with Grape

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Ruby 100.0%