adding a small API to a web application

ruby-on-rails

Solution

The difference between a "classical" or API only application are pretty small. The API only app scales away some of the middleware and components that are not needed in an API.

Otherwise the steps of building the actual API components are pretty much identical.

You will want to start by choosing a different superclass for your API controllers. Your API controllers don't need all the junk on ApplicationController and you will be treating quite a few aspects such as authentication differently.

Rails 5 has `ActionController::API`, In previous versions you would use `ActionController::Metal` and include the modules needed.

# app/controllers/api_controller.rb
class ApiController < ActionController::API
  # Do whatever you would do in ApplicationController
end

You then setup your routes:

namespace :api, defaults: { format: :json } do
  resources :things
end

And controllers:

module API
  class ThingsController < ApiController

    before_action :set_thing, except: [:create, :index]

    def show
      render json: @thing
    end

    def index
      render json: @things = Thing.all
    end

    def create
      @thing = Thing.create(thing_params)

      if @thing.save
        head :created, location: [:api, @thing]
      else
        render json: @thing.errors, status: :bad_entity
      end
    end
    # ...
  end
end

There are quite a few aspects to building an API such as versioning and JSON serialization strategies and you'll find plenty of tutorials on the subject - just don't get hung up on the API only part.

Problem

I have a rails application with some standard routes, and I would like to add some API endpoints into it. I figure I just have to add some routes (probably under a `scope '/api'`), create some new controllers that extend `ActionController::API`, and then perhaps do something so rails magically knows how to render the JSON data. Are there any guides on how to do this? Everything I can find talks about creating 'API only' applications, but doesn't discuss adding a few API endpoints to an existing web application. edit: I am specifically looking for rails 5 solutions

Original source