Build beautiful APIs in RUby with JSONAPI::Resources

We can build beautiful and secored APIs in ruby using JSONAPI::Resources gem . Its JSONAPI complaint, highly congigurable, easy to change and with minimal lines of code. We can create resources with inbuilt CRUD APIs with configurable response data and headers. Home page is https://jsonapi-resources.com/. Github is https://github.com/cerebris/jsonapi-resources.

Installation

add gem 'jsonapi-resources to your Gemfile

Config

Modify your application_controller.rb file as

class ApplicationController < JSONAPI::ResourceController
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :null_session
end

Modify development.rb with “`ruby

Eager load code on boot so JSONAPI-Resources resources are loaded and processed globally

config.eager_load = true

This will prevent the server from returning the HTML formatted error messages when an exception happens.

config.considerallrequests_local = false ”`

Fix possible CORS issues using this link

Create Resources

For every model you want APIs, you need to create a resource. Normally we use app/resources directory. Resource file name is like [MODEL]_resource.rb.

# contact_resource.rb

class ContactResource < JSONAPI::Resource
  attributes :name_first, :name_last, :email, :twitter
  has_many :phone_numbers

   filter :contact
end

Routes Setup

Add the following to routes.rb

jsonapi_resources :contacts
jsonapi_resources :phone_numbers

Caching