SlideShare a Scribd company logo
1 of 27
Daniel Doubrovkine / Art.sy
dblock@dblock.org @dblockdotorg
Solid API or Else …




http://www.youtube.com/watch?v=l9vYE7B1_PU
The Rails Way: M(V)C

config/routes.rb

resources :artists

app/controllers/artists_controller.rb

class ArtistsController < ApplicationController
  def index
    @artists = …
    # all kinds of stuff that serves views
    respond_to do |format|
      format.html { @artists }
      format.json { render json: @artists.as_json }
     end
  end
End
The Rails Way: MVC
app/views/artists/index.json.erb

-@artists.each do |artist|
 {
    'first_name': '<%= @artist.first_name.to_json %>',
    'last_name': '<%= @artist.last_name.to_json %>'
 }
Occupy Rails?
»   Where does the API start and end?
»   How are we going to build API v2 on top of v1?
»   Is API testing the same as controller testing?
»   How much discipline are we going to need to keep sanity?
»   How will deal with more difficult problems?
    Caching, authentication, authorization …
Modern Web Applications: NoRails
»   MVC UI
»   RESTful API
»   Storage
Grape
»   API DSL                            class API < Grape::API
                                         version „1'
    rack-based / middleware
    http://github.com/intridea/grape
                                        namespace :artist
                                          get “:id” do
                                            Artist.find(params[:id]).as_json
                                          end
                                        end

                                         namespace :artists do
                                           get “/” do
                                             Artist.all.as_json
                                           end
                                         end
                                       end
Documentation
»   Developers Have the Attention Span of a Fish *
    * when reading documentation


»   Written in Markdown
    http://code.dblock.org/rendering-markdown-documents-in-rails


»   Reference will be Generated
»   API Sandboxes
    https://github.com/mmcnierney14/API-Sandbox


»   API Explorer
    https://github.com/mmcnierney14/API-Sandbox
Testing an API
# spec/spec_helper.rb



RSpec.configure do |config|
  config.include RSpec::Rails::RequestExampleGroup,
    :type => :request,
    :example_group => {
      :file_path => /spec/api/
    }
end




                  See “Writing Tests” @ https://github.com/intridea/grape
Mocking is for Java Programmers
describe "artworks" do
      before(:each) do
            login_as Fabricate(:admin)
      end
      describe "GET /api/v1/artwork/:slug" do
        it "returns an unpublished artwork" do
            artwork = Fabricate(:artwork, published: false)
            get "/api/v1/artwork/#{artwork.slug}"
            response.status.should == 200
            response.body.at_json_path(“id”).should == artwork.slug # Pathy!
        end
      end
  end
end
Version 1 Births Version 2
 »   Include Api_v1
 »   Folder-Driven Development (FDD)
     api/api_v1/…




      module Api_v1                                     module Api_v2
        version 'v1„                                      version 'v2„
        module Api_v1_Me                                  module Api_v1_Me
        module Api_v1_Artworks                            module Api_v2_Artworks
        # ...                                             # ...
      end                                               end


See “Modularizing Grape API” @ http://code.dblock.org/modularizing-a-ror-grape-api-multiple-versions
Exceptions Abort Flow
      »     Don’t question yourself, raise a hand.
       rescue_from :all, :backtrace => true

          error_format :json

          rescue_from Mongoid::Errors::Validations do |e|
            rack_response({ :message => e.message,
             :detail => e.document.errors,
             :backtrace => e.backtrace }.to_json)
            end
          end



See “Grape: trapping all exceptions within the API” @ http://code.dblock.org/grape-trapping-all-exceptions-within-the-api
Authentication Methods
»     XApp: Exchange client ID for an XApp token
      api/v1/api_xapp_auth.rb


»     OAuth 2.0: Browser-Based Redirects
      controllers/oauth_controller.rb


»     XAuth: Exchange credentials for an OAuth token
      controllers/oauth_controller.rb


»     Forms Login to Website
      devise/warden via user.rb



    See “Grape: API Authentication w/ Devise” @ http://code.dblock.org/grape-api-authentication-w-devise
Authenticated Users
»   Unauthenticated Calls
»   Authorized Apps
»   Logged In Users, RBAC

                      def authenticated_user
                          authenticated
                          error!('Unauthorized', 401) unless current_user
                      end
Object Identity
»       Everything has an ID
    »     Internal ID: BSON ObjectId
    »     External ID: humanly-readable ID

»       ID is the same for all API consumers
»       API consumers know of a single ID
    »     When do I use a Slug?

    »     When do I use BSON ObjectId?
JSON Formats
»   ActiveRecord as_json passes options recursively
    :all – all fields visible to the object’s owner

    :public – all fields visible to a user with :read permissions

    :short – enough fields visible to a user with :read permissions, used within a collection

»   JSON data can be grown incrementally
POST and PUT
»   Validate Input Parameters in Models
    save(hashie)
    valid_hash_fields :first, :last
Authorization
»   Admins have :create, :read, :update, :delete on everything, also
    known as :manage

»   Partners have :manage on their partner data
    eg. partner location, get :all JSON

»   Users have :manage on their personal data
    eg. my collection, get :all JSON

»   Everyone has :read on public data
    eg. a published artwork, get :public JSON
Authorization Usage
»    Implemented w/ CanCan

     cannot :read, Artwork
     can :read, Artwork do |artwork|
       artwork.published
     end



    error!(„Unauthorized', 403) unless
       current_user.has_authorization_to?(:delete, artist)
Pagination
»   paginate(collection)
    »   :offset or :page
    »   :size




          Pagination Helper for Grape @ https://gist.github.com/1335242
Logging
»   Implemented as Rack Middleware

»   Logs API Calls
Caching
»   Implemented w/Rails Cache / Memcached
»   Key based on Class and Identity
    »   Cache Locally
    »   Invalidate Aggressively
Cache Busting
»   IE9




                See “IE9: Cache-Busting with Grape Middleware” @
          http://code.dblock.org/ie9-cache-busting-with-grape-middleware
Instrumentation
»   See API Stats in New Relic
    config/initializers/new_relic_agent_instrumentation_api.rb




                  See “New Relic: Performance Instrumentaiton w/ Grape” @
         http://code.dblock.org/new-relic-performance-instrumentation-with-grape-api
Performance
»   Trends
Next
»   Deep Data
»   Caching in JSON
»   Generated Documentation
How to design a good API and why it matters (Joshua Bloch)
http://www.youtube.com/watch?v=aAb7hSCtvGw




1. Do one thing well
2. API is a Language, names matter
3. Documentation matters
4. Minimize mutability
5. Don’t make the client do anything the API could do

More Related Content

What's hot

BDD testing with cucumber
BDD testing with cucumberBDD testing with cucumber
BDD testing with cucumberDaniel Kummer
 
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)hyun soomyung
 
CI CD Jenkins for Swift Deployment
CI CD Jenkins for Swift DeploymentCI CD Jenkins for Swift Deployment
CI CD Jenkins for Swift DeploymentBintang Thunder
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
잘 키운 모노리스 하나 열 마이크로서비스 안 부럽다
잘 키운 모노리스 하나 열 마이크로서비스 안 부럽다잘 키운 모노리스 하나 열 마이크로서비스 안 부럽다
잘 키운 모노리스 하나 열 마이크로서비스 안 부럽다Arawn Park
 
Scala API - Azure Event Hub Integration
Scala API - Azure Event Hub IntegrationScala API - Azure Event Hub Integration
Scala API - Azure Event Hub IntegrationBraja Krishna Das
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debateRestlet
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JSCakra Danu Sedayu
 
Open Source Logging and Monitoring Tools
Open Source Logging and Monitoring ToolsOpen Source Logging and Monitoring Tools
Open Source Logging and Monitoring ToolsPhase2
 
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaAndroid | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaJAX London
 
Walking through the Spring Stack for Apache Kafka with Soby Chacko | Kafka S...
 Walking through the Spring Stack for Apache Kafka with Soby Chacko | Kafka S... Walking through the Spring Stack for Apache Kafka with Soby Chacko | Kafka S...
Walking through the Spring Stack for Apache Kafka with Soby Chacko | Kafka S...HostedbyConfluent
 
OpenAPI development with Python
OpenAPI development with PythonOpenAPI development with Python
OpenAPI development with PythonTakuro Wada
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Steve Pember
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golangBasil N G
 
PPT on Android Applications
PPT on Android ApplicationsPPT on Android Applications
PPT on Android ApplicationsAshish Agarwal
 
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewaySpring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewayIván López Martín
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 

What's hot (20)

BDD testing with cucumber
BDD testing with cucumberBDD testing with cucumber
BDD testing with cucumber
 
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
 
CI CD Jenkins for Swift Deployment
CI CD Jenkins for Swift DeploymentCI CD Jenkins for Swift Deployment
CI CD Jenkins for Swift Deployment
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
잘 키운 모노리스 하나 열 마이크로서비스 안 부럽다
잘 키운 모노리스 하나 열 마이크로서비스 안 부럽다잘 키운 모노리스 하나 열 마이크로서비스 안 부럽다
잘 키운 모노리스 하나 열 마이크로서비스 안 부럽다
 
Scala API - Azure Event Hub Integration
Scala API - Azure Event Hub IntegrationScala API - Azure Event Hub Integration
Scala API - Azure Event Hub Integration
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debate
 
expense maneger
expense maneger expense maneger
expense maneger
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Open Source Logging and Monitoring Tools
Open Source Logging and Monitoring ToolsOpen Source Logging and Monitoring Tools
Open Source Logging and Monitoring Tools
 
Hybrid mobile app
Hybrid mobile appHybrid mobile app
Hybrid mobile app
 
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaAndroid | Android Activity Launch Modes and Tasks | Gonçalo Silva
Android | Android Activity Launch Modes and Tasks | Gonçalo Silva
 
Walking through the Spring Stack for Apache Kafka with Soby Chacko | Kafka S...
 Walking through the Spring Stack for Apache Kafka with Soby Chacko | Kafka S... Walking through the Spring Stack for Apache Kafka with Soby Chacko | Kafka S...
Walking through the Spring Stack for Apache Kafka with Soby Chacko | Kafka S...
 
OpenAPI development with Python
OpenAPI development with PythonOpenAPI development with Python
OpenAPI development with Python
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
 
Airflow for Beginners
Airflow for BeginnersAirflow for Beginners
Airflow for Beginners
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golang
 
PPT on Android Applications
PPT on Android ApplicationsPPT on Android Applications
PPT on Android Applications
 
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud GatewaySpring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
Spring IO 2023 - Dynamic OpenAPIs with Spring Cloud Gateway
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 

Viewers also liked

Building an API using Grape
Building an API using GrapeBuilding an API using Grape
Building an API using Grapevisnu priya
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsJim Jeffers
 
The Hitchhiker’s Guide to StackOverflow
The Hitchhiker’s Guide to StackOverflowThe Hitchhiker’s Guide to StackOverflow
The Hitchhiker’s Guide to StackOverflowSafeDK
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type ScriptFolio3 Software
 
RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)
RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)
RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)K Tsukada
 
Rails5とAPIモードについての解説
Rails5とAPIモードについての解説Rails5とAPIモードについての解説
Rails5とAPIモードについての解説Fumiya Sakai
 
StackOverflow Architectural Overview
StackOverflow Architectural OverviewStackOverflow Architectural Overview
StackOverflow Architectural OverviewFolio3 Software
 
SPAに必要なJavaScriptFrameWork
SPAに必要なJavaScriptFrameWorkSPAに必要なJavaScriptFrameWork
SPAに必要なJavaScriptFrameWorkMizuho Sakamaki
 
Railsチュートリアルの歩き方 (第4版)
Railsチュートリアルの歩き方 (第4版)Railsチュートリアルの歩き方 (第4版)
Railsチュートリアルの歩き方 (第4版)Yohei Yasukawa
 
RESTful Web アプリの設計レビューの話
RESTful Web アプリの設計レビューの話RESTful Web アプリの設計レビューの話
RESTful Web アプリの設計レビューの話Takuto Wada
 

Viewers also liked (11)

Building an API using Grape
Building an API using GrapeBuilding an API using Grape
Building an API using Grape
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
 
The Hitchhiker’s Guide to StackOverflow
The Hitchhiker’s Guide to StackOverflowThe Hitchhiker’s Guide to StackOverflow
The Hitchhiker’s Guide to StackOverflow
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
 
RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)
RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)
RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)
 
Rails5とAPIモードについての解説
Rails5とAPIモードについての解説Rails5とAPIモードについての解説
Rails5とAPIモードについての解説
 
StackOverflow Architectural Overview
StackOverflow Architectural OverviewStackOverflow Architectural Overview
StackOverflow Architectural Overview
 
SPAに必要なJavaScriptFrameWork
SPAに必要なJavaScriptFrameWorkSPAに必要なJavaScriptFrameWork
SPAに必要なJavaScriptFrameWork
 
Railsチュートリアルの歩き方 (第4版)
Railsチュートリアルの歩き方 (第4版)Railsチュートリアルの歩き方 (第4版)
Railsチュートリアルの歩き方 (第4版)
 
Rest ful api設計入門
Rest ful api設計入門Rest ful api設計入門
Rest ful api設計入門
 
RESTful Web アプリの設計レビューの話
RESTful Web アプリの設計レビューの話RESTful Web アプリの設計レビューの話
RESTful Web アプリの設計レビューの話
 

Similar to Building RESTful APIs w/ Grape

Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发shaokun
 
FOXX - a Javascript application framework on top of ArangoDB
FOXX - a Javascript application framework on top of ArangoDBFOXX - a Javascript application framework on top of ArangoDB
FOXX - a Javascript application framework on top of ArangoDBArangoDB Database
 
Building Better Web APIs with Rails
Building Better Web APIs with RailsBuilding Better Web APIs with Rails
Building Better Web APIs with RailsAll Things Open
 
2011 a grape odyssey
2011   a grape odyssey2011   a grape odyssey
2011 a grape odysseyMike Hagedorn
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentNicolas Ledez
 
Serverless - Developers.IO 2019
Serverless - Developers.IO 2019Serverless - Developers.IO 2019
Serverless - Developers.IO 2019Shuji Watanabe
 
Денис Лебедев-Управление зависимостями с помощью CocoaPods
Денис Лебедев-Управление зависимостями с помощью CocoaPodsДенис Лебедев-Управление зависимостями с помощью CocoaPods
Денис Лебедев-Управление зависимостями с помощью CocoaPodsUA Mobile
 
FiNCのWeb API開発事情
FiNCのWeb API開発事情FiNCのWeb API開発事情
FiNCのWeb API開発事情Fumiya Shinozuka
 
From Ruby to Node.js
From Ruby to Node.jsFrom Ruby to Node.js
From Ruby to Node.jsjubilem
 
Making a small QA system with Docker
Making a small QA system with DockerMaking a small QA system with Docker
Making a small QA system with DockerNaoki AINOYA
 
Be a microservices hero
Be a microservices heroBe a microservices hero
Be a microservices heroOpenRestyCon
 
Scaling up development of a modular code base
Scaling up development of a modular code baseScaling up development of a modular code base
Scaling up development of a modular code baseRobert Munteanu
 
Ionic Framework - get up and running to build hybrid mobile apps
Ionic Framework - get up and running to build hybrid mobile appsIonic Framework - get up and running to build hybrid mobile apps
Ionic Framework - get up and running to build hybrid mobile appsAndreas Sahle
 
From Zero to Mongo, Art.sy Experience w/ MongoDB
From Zero to Mongo, Art.sy Experience w/ MongoDBFrom Zero to Mongo, Art.sy Experience w/ MongoDB
From Zero to Mongo, Art.sy Experience w/ MongoDBDaniel Doubrovkine
 
Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsMykyta Protsenko
 
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDB
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDBBattle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDB
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDBJesse Wolgamott
 
High quality ap is with api platform
High quality ap is with api platformHigh quality ap is with api platform
High quality ap is with api platformNelson Kopliku
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 

Similar to Building RESTful APIs w/ Grape (20)

Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
FOXX - a Javascript application framework on top of ArangoDB
FOXX - a Javascript application framework on top of ArangoDBFOXX - a Javascript application framework on top of ArangoDB
FOXX - a Javascript application framework on top of ArangoDB
 
Building Better Web APIs with Rails
Building Better Web APIs with RailsBuilding Better Web APIs with Rails
Building Better Web APIs with Rails
 
2011 a grape odyssey
2011   a grape odyssey2011   a grape odyssey
2011 a grape odyssey
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirent
 
Serverless - Developers.IO 2019
Serverless - Developers.IO 2019Serverless - Developers.IO 2019
Serverless - Developers.IO 2019
 
Play framework
Play frameworkPlay framework
Play framework
 
Денис Лебедев-Управление зависимостями с помощью CocoaPods
Денис Лебедев-Управление зависимостями с помощью CocoaPodsДенис Лебедев-Управление зависимостями с помощью CocoaPods
Денис Лебедев-Управление зависимостями с помощью CocoaPods
 
FiNCのWeb API開発事情
FiNCのWeb API開発事情FiNCのWeb API開発事情
FiNCのWeb API開発事情
 
From Ruby to Node.js
From Ruby to Node.jsFrom Ruby to Node.js
From Ruby to Node.js
 
Making a small QA system with Docker
Making a small QA system with DockerMaking a small QA system with Docker
Making a small QA system with Docker
 
Be a microservices hero
Be a microservices heroBe a microservices hero
Be a microservices hero
 
Scaling up development of a modular code base
Scaling up development of a modular code baseScaling up development of a modular code base
Scaling up development of a modular code base
 
Ionic Framework - get up and running to build hybrid mobile apps
Ionic Framework - get up and running to build hybrid mobile appsIonic Framework - get up and running to build hybrid mobile apps
Ionic Framework - get up and running to build hybrid mobile apps
 
From Zero to Mongo, Art.sy Experience w/ MongoDB
From Zero to Mongo, Art.sy Experience w/ MongoDBFrom Zero to Mongo, Art.sy Experience w/ MongoDB
From Zero to Mongo, Art.sy Experience w/ MongoDB
 
Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and Ops
 
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDB
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDBBattle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDB
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDB
 
High quality ap is with api platform
High quality ap is with api platformHigh quality ap is with api platform
High quality ap is with api platform
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 

More from Daniel Doubrovkine

The Future of Art @ Worlds Fair Nano
The Future of Art @ Worlds Fair NanoThe Future of Art @ Worlds Fair Nano
The Future of Art @ Worlds Fair NanoDaniel Doubrovkine
 
Nasdaq CTO Summit: Inspiring Team Leads to Give Away Legos
Nasdaq CTO Summit: Inspiring Team Leads to Give Away LegosNasdaq CTO Summit: Inspiring Team Leads to Give Away Legos
Nasdaq CTO Summit: Inspiring Team Leads to Give Away LegosDaniel Doubrovkine
 
Open-Source by Default, UN Community.camp
Open-Source by Default, UN Community.campOpen-Source by Default, UN Community.camp
Open-Source by Default, UN Community.campDaniel Doubrovkine
 
Taking Over Open Source Projects @ GoGaRuCo 2014
Taking Over Open Source Projects @ GoGaRuCo 2014Taking Over Open Source Projects @ GoGaRuCo 2014
Taking Over Open Source Projects @ GoGaRuCo 2014Daniel Doubrovkine
 
Tiling and Zooming ASCII Art @ iOSoho
Tiling and Zooming ASCII Art @ iOSohoTiling and Zooming ASCII Art @ iOSoho
Tiling and Zooming ASCII Art @ iOSohoDaniel Doubrovkine
 
The Other Side of Your Interview
The Other Side of Your InterviewThe Other Side of Your Interview
The Other Side of Your InterviewDaniel Doubrovkine
 
Hiring Engineers (the Artsy Way)
Hiring Engineers (the Artsy Way)Hiring Engineers (the Artsy Way)
Hiring Engineers (the Artsy Way)Daniel Doubrovkine
 
Building and Scaling a Test Driven Culture
Building and Scaling a Test Driven CultureBuilding and Scaling a Test Driven Culture
Building and Scaling a Test Driven CultureDaniel Doubrovkine
 
Introducing Remote Install Framework
Introducing Remote Install FrameworkIntroducing Remote Install Framework
Introducing Remote Install FrameworkDaniel Doubrovkine
 
Taming the Testing Beast - AgileDC 2012
Taming the Testing Beast - AgileDC 2012Taming the Testing Beast - AgileDC 2012
Taming the Testing Beast - AgileDC 2012Daniel Doubrovkine
 
GeneralAssemb.ly Summer Program: Tech from the Ground Up
GeneralAssemb.ly Summer Program: Tech from the Ground UpGeneralAssemb.ly Summer Program: Tech from the Ground Up
GeneralAssemb.ly Summer Program: Tech from the Ground UpDaniel Doubrovkine
 
Making Agile Choices in Software Technology
Making Agile Choices in Software TechnologyMaking Agile Choices in Software Technology
Making Agile Choices in Software TechnologyDaniel Doubrovkine
 

More from Daniel Doubrovkine (20)

The Future of Art @ Worlds Fair Nano
The Future of Art @ Worlds Fair NanoThe Future of Art @ Worlds Fair Nano
The Future of Art @ Worlds Fair Nano
 
Nasdaq CTO Summit: Inspiring Team Leads to Give Away Legos
Nasdaq CTO Summit: Inspiring Team Leads to Give Away LegosNasdaq CTO Summit: Inspiring Team Leads to Give Away Legos
Nasdaq CTO Summit: Inspiring Team Leads to Give Away Legos
 
Product Development 101
Product Development 101Product Development 101
Product Development 101
 
Open-Source by Default, UN Community.camp
Open-Source by Default, UN Community.campOpen-Source by Default, UN Community.camp
Open-Source by Default, UN Community.camp
 
Your First Slack Ruby Bot
Your First Slack Ruby BotYour First Slack Ruby Bot
Your First Slack Ruby Bot
 
Single Sign-On with Waffle
Single Sign-On with WaffleSingle Sign-On with Waffle
Single Sign-On with Waffle
 
How it All Goes Down
How it All Goes DownHow it All Goes Down
How it All Goes Down
 
Taking Over Open Source Projects @ GoGaRuCo 2014
Taking Over Open Source Projects @ GoGaRuCo 2014Taking Over Open Source Projects @ GoGaRuCo 2014
Taking Over Open Source Projects @ GoGaRuCo 2014
 
Mentoring Engineers & Humans
Mentoring Engineers & HumansMentoring Engineers & Humans
Mentoring Engineers & Humans
 
Tiling and Zooming ASCII Art @ iOSoho
Tiling and Zooming ASCII Art @ iOSohoTiling and Zooming ASCII Art @ iOSoho
Tiling and Zooming ASCII Art @ iOSoho
 
Artsy ♥ ASCII ART
Artsy ♥ ASCII ARTArtsy ♥ ASCII ART
Artsy ♥ ASCII ART
 
The Other Side of Your Interview
The Other Side of Your InterviewThe Other Side of Your Interview
The Other Side of Your Interview
 
Hiring Engineers (the Artsy Way)
Hiring Engineers (the Artsy Way)Hiring Engineers (the Artsy Way)
Hiring Engineers (the Artsy Way)
 
Mentoring 101 - the Artsy way
Mentoring 101 - the Artsy wayMentoring 101 - the Artsy way
Mentoring 101 - the Artsy way
 
Building and Scaling a Test Driven Culture
Building and Scaling a Test Driven CultureBuilding and Scaling a Test Driven Culture
Building and Scaling a Test Driven Culture
 
Introducing Remote Install Framework
Introducing Remote Install FrameworkIntroducing Remote Install Framework
Introducing Remote Install Framework
 
HackYale 0-60 in Startup Tech
HackYale 0-60 in Startup TechHackYale 0-60 in Startup Tech
HackYale 0-60 in Startup Tech
 
Taming the Testing Beast - AgileDC 2012
Taming the Testing Beast - AgileDC 2012Taming the Testing Beast - AgileDC 2012
Taming the Testing Beast - AgileDC 2012
 
GeneralAssemb.ly Summer Program: Tech from the Ground Up
GeneralAssemb.ly Summer Program: Tech from the Ground UpGeneralAssemb.ly Summer Program: Tech from the Ground Up
GeneralAssemb.ly Summer Program: Tech from the Ground Up
 
Making Agile Choices in Software Technology
Making Agile Choices in Software TechnologyMaking Agile Choices in Software Technology
Making Agile Choices in Software Technology
 

Recently uploaded

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Recently uploaded (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Building RESTful APIs w/ Grape

  • 1. Daniel Doubrovkine / Art.sy dblock@dblock.org @dblockdotorg
  • 2. Solid API or Else … http://www.youtube.com/watch?v=l9vYE7B1_PU
  • 3. The Rails Way: M(V)C config/routes.rb resources :artists app/controllers/artists_controller.rb class ArtistsController < ApplicationController def index @artists = … # all kinds of stuff that serves views respond_to do |format| format.html { @artists } format.json { render json: @artists.as_json } end end End
  • 4. The Rails Way: MVC app/views/artists/index.json.erb -@artists.each do |artist| { 'first_name': '<%= @artist.first_name.to_json %>', 'last_name': '<%= @artist.last_name.to_json %>' }
  • 5. Occupy Rails? » Where does the API start and end? » How are we going to build API v2 on top of v1? » Is API testing the same as controller testing? » How much discipline are we going to need to keep sanity? » How will deal with more difficult problems? Caching, authentication, authorization …
  • 6. Modern Web Applications: NoRails » MVC UI » RESTful API » Storage
  • 7. Grape » API DSL class API < Grape::API version „1' rack-based / middleware http://github.com/intridea/grape namespace :artist get “:id” do Artist.find(params[:id]).as_json end end namespace :artists do get “/” do Artist.all.as_json end end end
  • 8. Documentation » Developers Have the Attention Span of a Fish * * when reading documentation » Written in Markdown http://code.dblock.org/rendering-markdown-documents-in-rails » Reference will be Generated » API Sandboxes https://github.com/mmcnierney14/API-Sandbox » API Explorer https://github.com/mmcnierney14/API-Sandbox
  • 9. Testing an API # spec/spec_helper.rb RSpec.configure do |config| config.include RSpec::Rails::RequestExampleGroup, :type => :request, :example_group => { :file_path => /spec/api/ } end See “Writing Tests” @ https://github.com/intridea/grape
  • 10. Mocking is for Java Programmers describe "artworks" do before(:each) do login_as Fabricate(:admin) end describe "GET /api/v1/artwork/:slug" do it "returns an unpublished artwork" do artwork = Fabricate(:artwork, published: false) get "/api/v1/artwork/#{artwork.slug}" response.status.should == 200 response.body.at_json_path(“id”).should == artwork.slug # Pathy! end end end end
  • 11. Version 1 Births Version 2 » Include Api_v1 » Folder-Driven Development (FDD) api/api_v1/… module Api_v1 module Api_v2 version 'v1„ version 'v2„ module Api_v1_Me module Api_v1_Me module Api_v1_Artworks module Api_v2_Artworks # ... # ... end end See “Modularizing Grape API” @ http://code.dblock.org/modularizing-a-ror-grape-api-multiple-versions
  • 12. Exceptions Abort Flow » Don’t question yourself, raise a hand. rescue_from :all, :backtrace => true error_format :json rescue_from Mongoid::Errors::Validations do |e| rack_response({ :message => e.message, :detail => e.document.errors, :backtrace => e.backtrace }.to_json) end end See “Grape: trapping all exceptions within the API” @ http://code.dblock.org/grape-trapping-all-exceptions-within-the-api
  • 13. Authentication Methods » XApp: Exchange client ID for an XApp token api/v1/api_xapp_auth.rb » OAuth 2.0: Browser-Based Redirects controllers/oauth_controller.rb » XAuth: Exchange credentials for an OAuth token controllers/oauth_controller.rb » Forms Login to Website devise/warden via user.rb See “Grape: API Authentication w/ Devise” @ http://code.dblock.org/grape-api-authentication-w-devise
  • 14. Authenticated Users » Unauthenticated Calls » Authorized Apps » Logged In Users, RBAC def authenticated_user authenticated error!('Unauthorized', 401) unless current_user end
  • 15. Object Identity » Everything has an ID » Internal ID: BSON ObjectId » External ID: humanly-readable ID » ID is the same for all API consumers » API consumers know of a single ID » When do I use a Slug? » When do I use BSON ObjectId?
  • 16. JSON Formats » ActiveRecord as_json passes options recursively :all – all fields visible to the object’s owner :public – all fields visible to a user with :read permissions :short – enough fields visible to a user with :read permissions, used within a collection » JSON data can be grown incrementally
  • 17. POST and PUT » Validate Input Parameters in Models save(hashie) valid_hash_fields :first, :last
  • 18. Authorization » Admins have :create, :read, :update, :delete on everything, also known as :manage » Partners have :manage on their partner data eg. partner location, get :all JSON » Users have :manage on their personal data eg. my collection, get :all JSON » Everyone has :read on public data eg. a published artwork, get :public JSON
  • 19. Authorization Usage » Implemented w/ CanCan cannot :read, Artwork can :read, Artwork do |artwork| artwork.published end error!(„Unauthorized', 403) unless current_user.has_authorization_to?(:delete, artist)
  • 20. Pagination » paginate(collection) » :offset or :page » :size Pagination Helper for Grape @ https://gist.github.com/1335242
  • 21. Logging » Implemented as Rack Middleware » Logs API Calls
  • 22. Caching » Implemented w/Rails Cache / Memcached » Key based on Class and Identity » Cache Locally » Invalidate Aggressively
  • 23. Cache Busting » IE9 See “IE9: Cache-Busting with Grape Middleware” @ http://code.dblock.org/ie9-cache-busting-with-grape-middleware
  • 24. Instrumentation » See API Stats in New Relic config/initializers/new_relic_agent_instrumentation_api.rb See “New Relic: Performance Instrumentaiton w/ Grape” @ http://code.dblock.org/new-relic-performance-instrumentation-with-grape-api
  • 25. Performance » Trends
  • 26. Next » Deep Data » Caching in JSON » Generated Documentation
  • 27. How to design a good API and why it matters (Joshua Bloch) http://www.youtube.com/watch?v=aAb7hSCtvGw 1. Do one thing well 2. API is a Language, names matter 3. Documentation matters 4. Minimize mutability 5. Don’t make the client do anything the API could do