Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Build APIs with Ruby, on or off Rails

JP Boily
February 24, 2016

Build APIs with Ruby, on or off Rails

You want to know how to build great Ruby on Rails APIs but also with other tool? Where should you start? What are the great tools to build, maintain, test and document an API? I'll talk about various tools like Rails, Grape, ActiveModel::Serializer and more! Will we go funky and try Lotus or something else too? Maybe! After this talk, you will know great toolsets for your next API project, their pros and cons and you'll be ready to dive right in!

Talk given at ConFoo 2016, in Montreal.

https://confoo.ca/en/2016/session/build-apis-with-ruby-on-or-off-rails

JP Boily

February 24, 2016
Tweet

More Decks by JP Boily

Other Decks in Technology

Transcript

  1. metrics.watch | freeGoogleAnalyticsCourse.com Build APIs with Ruby, on or off

    Rails Jean-Philippe Boily @jipiboily | jipiboily.com Founder of Metrics Watch http://metrics.watch
  2. metrics.watch | freeGoogleAnalyticsCourse.com whoami Jean-Philippe “JP” Boily Founder of Metrics

    Watch SaaS consultant Software Engineer with experience working remotely for US- based SaaS startups Last one was Rainforest QA (YC backed)
  3. metrics.watch | freeGoogleAnalyticsCourse.com Metrics Watch Alerts for Google Analytics in

    near real-time. Support for custom metrics, filters, alert templates, etc. Check us out! http://metrics.watch PS: I have stickers!
  4. metrics.watch | freeGoogleAnalyticsCourse.com I am assuming that you know… …

    how web works … how routing works in general … how to query data and present it in some ways (i.e., HTML, JSON or XML) … some Ruby
  5. metrics.watch | freeGoogleAnalyticsCourse.com Rack Rack: a Ruby Webserver Interface. Super

    basic, probably avoid to use directly. # my_rack_app.rb require 'rack' app = Proc.new do |env| ['200', {'Content-Type' => 'text/html'}, ['A barebones rack app.']] end Rack::Handler::WEBrick.run app
  6. metrics.watch | freeGoogleAnalyticsCourse.com Sinatra Not a framework, a library. Light,

    very light. You want more? Add it yourself! require 'sinatra' get '/hi' do { hello: 'world' } end
  7. metrics.watch | freeGoogleAnalyticsCourse.com Grape “micro-framework” for APIs It’s a DSL.

    Validation, versioning and more built-in. You want more? Add it yourself!
  8. module Twitter class API < Grape::API version 'v1', using: :header,

    vendor: 'twitter' format :json prefix :api helpers do def current_user @current_user ||= User.authorize!(env) end def authenticate! error!('401 Unauthorized', 401) unless current_user end end resource :statuses do desc 'Return a public timeline.' get :public_timeline do Status.limit(20) end desc 'Create a status.' params do requires :status, type: String, desc: 'Your status.' end post do authenticate! Status.create!({ user: current_user, text: params[:status] }) end end end end
  9. metrics.watch | freeGoogleAnalyticsCourse.com Hanami (formerly Lotus.rb) Plain Ruby modular web

    framework Seems to have a very nice architecture approach. http://lucaguidi.com/2015/11/24/json-api-apps-with-lotus.html http://lucaguidi.com/2015/12/09/25000-requests-per-second-for-rack-json-api-with-mruby.html
  10. metrics.watch | freeGoogleAnalyticsCourse.com Hanami # controllers/books.rb module Bookshelf::API::Controllers::Books class Index

    include Lotus::Action def call(params) end end end # config/routes.rb: get '/books', to: 'books#index'
  11. metrics.watch | freeGoogleAnalyticsCourse.com Rails Full featured framework with everything you

    might need. It just works™. Best in breed monolith builder!
  12. metrics.watch | freeGoogleAnalyticsCourse.com Sinatra and Grape…in Rails? FYI, you can

    mount any Rack-based app in Rails to benefit of some of the Rails features
  13. metrics.watch | freeGoogleAnalyticsCourse.com Rails, just Rails You have a Rails

    app already? Use it.
 You don’t have a Ruby app at all? Start with Rails API (if you know you won’t be serving any HTML pages)
  14. metrics.watch | freeGoogleAnalyticsCourse.com Why? •It just works. Almost nothing to

    configure. •Reload in development easily. •Easy deployment. •Conventions makes it easy to onboard people. •Takes care of many security concerns for you.
  15. metrics.watch | freeGoogleAnalyticsCourse.com Routing (& versionning) # config/routes.rb Rails.application.routes.draw do

    namespace :api do # /api namespace :v1 do # /api/v1 get 'metrics_providers', to: 'metrics_providers#index' # /api/v1/alerts resources :watchers, path: 'alerts' end end end
  16. metrics.watch | freeGoogleAnalyticsCourse.com Controllers class Api::V1::MetricsProvidersController < ApplicationController def index

    providers = current_account.metrics_providers render json: providers end end This is not going to be nice, by default!
  17. metrics.watch | freeGoogleAnalyticsCourse.com ActiveModel::Serializer Part of the initial Rails API

    initiative. Not a DSL, just Ruby. No setup. Weird state right now. https://github.com/rails-api/active_model_serializers
  18. metrics.watch | freeGoogleAnalyticsCourse.com ActiveModel::Serializer class WatcherSerializer < ActiveModel::Serializer attributes :id,

    :name, :metric_name, :threshold, :interval_type, :email_recipients attribute :watcher_type, key: :comparison_type def email_recipients object.destination_emails.map {|de| de.settings['email'] } end end
  19. metrics.watch | freeGoogleAnalyticsCourse.com ActiveModel::Serializer { "data": { "id": "150", "type":

    "watchers", "attributes": { "name": "Traffic Spike (near real-time)", "metric_name": "ga:sessions", "threshold": 250, "interval_type": "today", "google_analytics_profile_id": "123", "metrics_provider_id": 30, "email_recipients": [ "[email protected]" ], "google_analytics_filters": null, "comparison_type": "goes_above" } } }
  20. metrics.watch | freeGoogleAnalyticsCourse.com Jbuilder Has the worst name. In Rails

    Gemfiles by default. I don’t like it…but it works.
  21. metrics.watch | freeGoogleAnalyticsCourse.com Jbuilder # app/views/message/show.json.jbuilder json.content format_content(@message.content) json.(@message, :created_at,

    :updated_at) json.author do json.name @message.creator.name.familiar json.url url_for(@message.creator, format: :json) end if current_user.admin? json.visitors calculate_visitors(@message) end json.comments @message.comments, :content, :created_at json.attachments @message.attachments do |attachment| json.filename attachment.filename json.url url_for(attachment) end
  22. metrics.watch | freeGoogleAnalyticsCourse.com brainstem Never used it and seems massively

    overkill for 90%+ of the use cases. (not half of the example fits in this screen) https://github.com/mavenlink/brainstem
  23. metrics.watch | freeGoogleAnalyticsCourse.com Build your own serializers class Watcher <

    ActiveRecord::Base def as_json { id: id, name: name, metric_name: metric_name, threshold: threshold, interval_type: interval_type } end end
  24. metrics.watch | freeGoogleAnalyticsCourse.com KISS Internal only, for connected users to

    the Rails app? Just use what’s there (i.e., Devise, …) For external APIs just create one API key per account or user (to start with)
  25. metrics.watch | freeGoogleAnalyticsCourse.com Model validations? Yes! Translate that into a

    JSON friendly format and you’re done. Just be consistent with your format.
  26. metrics.watch | freeGoogleAnalyticsCourse.com Status codes 200? 201? 202? 401? Semantic

    usage, please! https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  27. metrics.watch | freeGoogleAnalyticsCourse.com What to test? Authentication Output format Core

    logic with different contexts Service objets? Just make sure it’s called!
  28. metrics.watch | freeGoogleAnalyticsCourse.com Apiary Create, design, mock & test an

    API in seconds Interactive doc with cURL & code generation
  29. metrics.watch | freeGoogleAnalyticsCourse.com Blueprint “API Blueprint. A powerful high-level API

    description language for web APIs.” https://apiblueprint.org/
  30. metrics.watch | freeGoogleAnalyticsCourse.com I did not talk about… • JSON

    API - http://jsonapi.org/ • http://json-schema.org/ • Hypermedia API • Caching …but read about those!
  31. metrics.watch | freeGoogleAnalyticsCourse.com Key takeaways •Use tools that exists, works

    well and have a long track record of success •Use Rails •KISS
  32. GET AWESOME GIFTS freeGAcourse.com • free course “How to get

    the most out of Google Analytics” • longer trial for Metrics Watch (1 month instead of 14 days) ConFooLove.com • Slides for my two talks at ConFoo • testing toolbox cheatsheet • API toolbox cheatsheet • early invite to join my free email course about distributed teams, for pre-launch THANKS