Build Rails 5 API (Part 1)

Create new project using "--api" mode

mkdir myapi
cd myapi
touch .ruby-version
touch .ruby-gemset
echo ruby-2.7.0 > .ruby-version
echo myapi > .ruby-gemset
cd ../myapi
gem install rails -v 6.0.0
rails new . -T --api
gem install bundler
bundle
rake db:create db:migrate

Create model Book

rails g migration CreateBooks
class CreateBooks < ActiveRecord::Migration[5.0]
  def change
    create_table :books do |t|
      t.string :title
      t.float :price
      t.string :author
    end
  end
end
# config/initializers/active_model_serializer.rb
ActiveModel::Serializer.config.adapter = :json
# config/routes.rb
Rails.application.routes.draw do
  resources :books
end
# app/models/book.rb
class Book < ActiveRecord::Base
end

Don't forget create a few records
 
Serializing JSON responses

# https://github.com/rails-api/active_model_serializers
gem 'active_model_serializers'
rails g serializer book
# app/serializers/book_serializer.rb
class BookSerializer < ActiveModel::Serializer
  attributes :id, :custom_title, :price

  def custom_title
    "#{ @object.title } (#{ @object.author })"
  end
end
# app/controllers/books_controller.rb
class BooksController < ApplicationController
  def index
    render json: Book.all
  end
end

Enjoy your first API
http://localhost:3000/books.json