Rails API

Rails API

API only applications with Rails API

E0fe062ff7f5d75b8e13773340370db5?s=128

Saurabh Bhatia

February 22, 2014
Tweet

Transcript

  1. API Only Applications with rails-api Saurabh Bhatia http://fedible.org

  2. what? $ gem install rails-api Rails minus some middleware stack,

    actionpack modules and template generation.
  3. why? • Lightweight • Fast • API only application –

    backend for mobile app, web application is just another client (e.g. html, angular.js ) to a json api.
  4. Generating a new app $ rails-api new notesapp

  5. No views

  6. rails-api controller app/controllers/application_controller.rb class ApplicationController < ActionController::API end

  7. controller actions def index @posts = Post.all render json: @posts

    end • rails-api uses render instead of respond methods. • Let's see how to include those.
  8. extending controller class ApplicationController < ActionController::API include ActionController::MimeResponds include ActionController::ImplicitRender

    end • MimeResponds and Implicit render provide support for respond_to, respond_with.
  9. middleware

  10. extending middleware $config/application.rb require File.expand_path('../boot', __FILE__) require 'rails/all'. Bundler.require(:default, Rails.env)

    module Notesapp class Application < Rails::Application config.middleware.use ActionDispatch::Flash end end
  11. extended

  12. serializers • gem "active_model_serializers" • $rails g serialzer post •

    $ ls assets controllers mailers models serializers app$ cd serializers/ app/serializers$ ls post_serializer.rb
  13. serialzers class PostSerializer < ActiveModel::Serializer attributes :title, :body end •

    JSON Response {"posts": [{"id":1,"title":"First Post","body":"Test"}, {"id":2,"title":"Second Post","body":"Another Test"}] }
  14. Shameless Plug : Rails 4 application development

  15. Thank you 謝謝