Rails API Basics

Episode #49 by Teacher's Avatar David Kimura

Summary

A brief introduction on Rails API. Learn how to create an API application and setup the routes. This episode is paving the way for more in depth looks into Rails API.
rails api routes 5:28

Resources

Summary

# Console
rails new APP_NAME --api

# Console
rake routes
   Prefix Verb   URI Pattern          Controller#Action
api_users GET    /users(.:format)     api/users#index {:subdomain=>"api"}
          POST   /users(.:format)     api/users#create {:subdomain=>"api"}
 api_user GET    /users/:id(.:format) api/users#show {:subdomain=>"api"}
          PATCH  /users/:id(.:format) api/users#update {:subdomain=>"api"}
          PUT    /users/:id(.:format) api/users#update {:subdomain=>"api"}
          DELETE /users/:id(.:format) api/users#destroy {:subdomain=>"api"}

# routes.rb
Rails.application.routes.draw do
  namespace :api, path: '/', constraints: { subdomain: 'api' } do
    resources :users
  end

  # Same as doing:
  # constraints subdomain: 'api' do
  #   namespace :api, path: '/' do
  #     resources :users
  #   end
  # end
end

# controllers/api/users_controller.rb
module Api
  class UsersController < ApplicationController
   ...
  end
end

# config/application.rb
module ApiDemo
  class Application < Rails::Application
    # Only loads a smaller set of middleware suitable for API only apps.
    # Middleware like session, flash, cookies can be added back manually.
    # Skip views, helpers and assets when generating a new resource.
    config.api_only = true
  end
end