Build Beautiful APIs in Ruby with JSONAPI::Resources

Creating secure and elegant APIs in Ruby is made simple with the JSONAPI::Resources gem. This gem adheres to the JSONAPI standard, is highly configurable, easy to modify, and requires minimal lines of code. It enables the creation of resources with built-in CRUD APIs and customizable response data and headers. Visit the home page and the GitHub repository for more information.

Installation

Add the gem to your Gemfile:

gem 'jsonapi-resources'

Then run:

bundle install

Configuration

Application Controller

Modify your application_controller.rb file:

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

Development Environment

Update config/environments/development.rb:

# Eager load code on boot so JSONAPI::Resources resources are loaded and processed globally
config.eager_load = true

# Prevent the server from returning HTML formatted error messages on exceptions
config.consider_all_requests_local = false

CORS Issues

Fix potential CORS issues by following the guide on CORS.

Creating Resources

For every model you want to expose via APIs, you need to create a resource. Typically, resources are placed in the app/resources directory. The resource file name should follow the format [MODEL]_resource.rb.

Example for a Contact model:

# app/resources/contact_resource.rb

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

  filter :contact
end

Setting Up Routes

Add the following to config/routes.rb:

Rails.application.routes.draw do
  jsonapi_resources :contacts
  jsonapi_resources :phone_numbers
end

Caching

JSONAPI::Resources supports caching for performance improvements. Refer to the official documentation for detailed information on how to configure caching in your application.


By following these steps, you can easily set up a JSONAPI-compliant API in Ruby with the JSONAPI::Resources gem. This setup ensures a standardized, efficient, and maintainable approach to building APIs. For more detailed guidance, visit the official documentation.