Building RESTful APIs w/ Grape

Daniel Doubrovkine
Daniel DoubrovkineCTO, Artsy.net at Cornell Tech
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
1 of 27

Recommended

Image Processing on Delta Lake by
Image Processing on Delta LakeImage Processing on Delta Lake
Image Processing on Delta LakeDatabricks
1.5K views25 slides
202201 AWS Black Belt Online Seminar Apache Spark Performnace Tuning for AWS ... by
202201 AWS Black Belt Online Seminar Apache Spark Performnace Tuning for AWS ...202201 AWS Black Belt Online Seminar Apache Spark Performnace Tuning for AWS ...
202201 AWS Black Belt Online Seminar Apache Spark Performnace Tuning for AWS ...Amazon Web Services Japan
4.4K views108 slides
Django Web Application Security by
Django Web Application SecurityDjango Web Application Security
Django Web Application Securitylevigross
6.7K views24 slides
Sinatra Rack And Middleware by
Sinatra Rack And MiddlewareSinatra Rack And Middleware
Sinatra Rack And MiddlewareBen Schwarz
16.9K views82 slides
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015 by
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015
XSS Attacks Exploiting XSS Filter by Masato Kinugawa - CODE BLUE 2015CODE BLUE
6.5K views84 slides
"Spark Search" - In-memory, Distributed Search with Lucene, Spark, and Tachyo... by
"Spark Search" - In-memory, Distributed Search with Lucene, Spark, and Tachyo..."Spark Search" - In-memory, Distributed Search with Lucene, Spark, and Tachyo...
"Spark Search" - In-memory, Distributed Search with Lucene, Spark, and Tachyo...Lucidworks
11K views61 slides

More Related Content

What's hot

Exactly once with spark streaming by
Exactly once with spark streamingExactly once with spark streaming
Exactly once with spark streamingQuentin Ambard
1.6K views57 slides
Building a Scalable Web Crawler with Hadoop by
Building a Scalable Web Crawler with HadoopBuilding a Scalable Web Crawler with Hadoop
Building a Scalable Web Crawler with HadoopHadoop User Group
34.9K views17 slides
CSS Dasar #5 : Text Styling by
CSS Dasar #5 : Text StylingCSS Dasar #5 : Text Styling
CSS Dasar #5 : Text StylingSandhika Galih
2.6K views13 slides
The never-ending REST API design debate by
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debateRestlet
10.1K views93 slides
Hyperloglog Project by
Hyperloglog ProjectHyperloglog Project
Hyperloglog ProjectKendrick Lo
9.8K views23 slides
深入淺出 AWS 大數據工具 by
深入淺出 AWS 大數據工具深入淺出 AWS 大數據工具
深入淺出 AWS 大數據工具Amazon Web Services
2.3K views55 slides

What's hot(20)

Exactly once with spark streaming by Quentin Ambard
Exactly once with spark streamingExactly once with spark streaming
Exactly once with spark streaming
Quentin Ambard1.6K views
Building a Scalable Web Crawler with Hadoop by Hadoop User Group
Building a Scalable Web Crawler with HadoopBuilding a Scalable Web Crawler with Hadoop
Building a Scalable Web Crawler with Hadoop
Hadoop User Group34.9K views
CSS Dasar #5 : Text Styling by Sandhika Galih
CSS Dasar #5 : Text StylingCSS Dasar #5 : Text Styling
CSS Dasar #5 : Text Styling
Sandhika Galih2.6K views
The never-ending REST API design debate by Restlet
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debate
Restlet10.1K views
Hyperloglog Project by Kendrick Lo
Hyperloglog ProjectHyperloglog Project
Hyperloglog Project
Kendrick Lo9.8K views
엘라스틱서치, 로그스태시, 키바나 by 종민 김
엘라스틱서치, 로그스태시, 키바나엘라스틱서치, 로그스태시, 키바나
엘라스틱서치, 로그스태시, 키바나
종민 김39.9K views
LuceneRDD for (Geospatial) Search and Entity Linkage by zouzias
LuceneRDD for (Geospatial) Search and Entity LinkageLuceneRDD for (Geospatial) Search and Entity Linkage
LuceneRDD for (Geospatial) Search and Entity Linkage
zouzias2.4K views
Getting Started with HTML5 in Tech Com (STC 2012) by Peter Lubbers
Getting Started with HTML5 in Tech Com (STC 2012)Getting Started with HTML5 in Tech Com (STC 2012)
Getting Started with HTML5 in Tech Com (STC 2012)
Peter Lubbers45.4K views
빠른 모바일 인증 구현을 위한 Amazon Cognito 서비스 소개 :: 윤석찬 - AWS Monthly Webinar by Amazon Web Services Korea
빠른 모바일 인증 구현을 위한 Amazon Cognito 서비스 소개 :: 윤석찬 - AWS Monthly Webinar빠른 모바일 인증 구현을 위한 Amazon Cognito 서비스 소개 :: 윤석찬 - AWS Monthly Webinar
빠른 모바일 인증 구현을 위한 Amazon Cognito 서비스 소개 :: 윤석찬 - AWS Monthly Webinar
Chapter 18: Transitions, Transforms, and Animation by Steve Guinan
Chapter 18: Transitions, Transforms, and AnimationChapter 18: Transitions, Transforms, and Animation
Chapter 18: Transitions, Transforms, and Animation
Steve Guinan269 views
Spray Json and MongoDB Queries: Insights and Simple Tricks. by Andrii Lashchenko
Spray Json and MongoDB Queries: Insights and Simple Tricks.Spray Json and MongoDB Queries: Insights and Simple Tricks.
Spray Json and MongoDB Queries: Insights and Simple Tricks.
Andrii Lashchenko1.1K views
Spark Summit East 2015 Advanced Devops Student Slides by Databricks
Spark Summit East 2015 Advanced Devops Student SlidesSpark Summit East 2015 Advanced Devops Student Slides
Spark Summit East 2015 Advanced Devops Student Slides
Databricks17.7K views
Apache Calcite: A Foundational Framework for Optimized Query Processing Over ... by Julian Hyde
Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...
Apache Calcite: A Foundational Framework for Optimized Query Processing Over ...
Julian Hyde2.3K views
8 Ways to Hack a WordPress website by SiteGround.com
8 Ways to Hack a WordPress website8 Ways to Hack a WordPress website
8 Ways to Hack a WordPress website
SiteGround.com204.8K views
Polyglot payloads in practice by avlidienbrunn at HackPra by Mathias Karlsson
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPra
Mathias Karlsson14.5K views
Apache Calcite: One planner fits all by Julian Hyde
Apache Calcite: One planner fits allApache Calcite: One planner fits all
Apache Calcite: One planner fits all
Julian Hyde6.7K views
AWS Summit Seoul 2023 | 실시간 CDC 데이터 처리! Modern Transactional Data Lake 구축하기 by Amazon Web Services Korea
AWS Summit Seoul 2023 | 실시간 CDC 데이터 처리! Modern Transactional Data Lake 구축하기AWS Summit Seoul 2023 | 실시간 CDC 데이터 처리! Modern Transactional Data Lake 구축하기
AWS Summit Seoul 2023 | 실시간 CDC 데이터 처리! Modern Transactional Data Lake 구축하기
Introduction to elasticsearch by hypto
Introduction to elasticsearchIntroduction to elasticsearch
Introduction to elasticsearch
hypto2.3K views

Viewers also liked

Building an API using Grape by
Building an API using GrapeBuilding an API using Grape
Building an API using Grapevisnu priya
1.1K views14 slides
Building Mobile Friendly APIs in Rails by
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsJim Jeffers
2.8K views110 slides
The Hitchhiker’s Guide to StackOverflow by
The Hitchhiker’s Guide to StackOverflowThe Hitchhiker’s Guide to StackOverflow
The Hitchhiker’s Guide to StackOverflowSafeDK
342 views12 slides
All You Need to Know About Type Script by
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type ScriptFolio3 Software
737 views27 slides
RESTful開発フロントエンド編(SPA・AltJS・フレームワーク) by
RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)
RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)K Tsukada
4.3K views45 slides
Rails5とAPIモードについての解説 by
Rails5とAPIモードについての解説Rails5とAPIモードについての解説
Rails5とAPIモードについての解説Fumiya Sakai
11.3K views13 slides

Viewers also liked(11)

Building an API using Grape by visnu priya
Building an API using GrapeBuilding an API using Grape
Building an API using Grape
visnu priya1.1K views
Building Mobile Friendly APIs in Rails by Jim Jeffers
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
Jim Jeffers2.8K views
The Hitchhiker’s Guide to StackOverflow by SafeDK
The Hitchhiker’s Guide to StackOverflowThe Hitchhiker’s Guide to StackOverflow
The Hitchhiker’s Guide to StackOverflow
SafeDK 342 views
All You Need to Know About Type Script by Folio3 Software
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
Folio3 Software737 views
RESTful開発フロントエンド編(SPA・AltJS・フレームワーク) by K Tsukada
RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)
RESTful開発フロントエンド編(SPA・AltJS・フレームワーク)
K Tsukada4.3K views
Rails5とAPIモードについての解説 by Fumiya Sakai
Rails5とAPIモードについての解説Rails5とAPIモードについての解説
Rails5とAPIモードについての解説
Fumiya Sakai11.3K views
StackOverflow Architectural Overview by Folio3 Software
StackOverflow Architectural OverviewStackOverflow Architectural Overview
StackOverflow Architectural Overview
Folio3 Software4.5K views
SPAに必要なJavaScriptFrameWork by Mizuho Sakamaki
SPAに必要なJavaScriptFrameWorkSPAに必要なJavaScriptFrameWork
SPAに必要なJavaScriptFrameWork
Mizuho Sakamaki7.1K views
Railsチュートリアルの歩き方 (第4版) by Yohei Yasukawa
Railsチュートリアルの歩き方 (第4版)Railsチュートリアルの歩き方 (第4版)
Railsチュートリアルの歩き方 (第4版)
Yohei Yasukawa427.8K views
RESTful Web アプリの設計レビューの話 by Takuto Wada
RESTful Web アプリの設計レビューの話RESTful Web アプリの設計レビューの話
RESTful Web アプリの設計レビューの話
Takuto Wada72.2K views

Similar to Building RESTful APIs w/ Grape

Rails web api 开发 by
Rails web api 开发Rails web api 开发
Rails web api 开发shaokun
1.3K views45 slides
FOXX - a Javascript application framework on top of ArangoDB by
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
35.8K views33 slides
Building Better Web APIs with Rails by
Building Better Web APIs with RailsBuilding Better Web APIs with Rails
Building Better Web APIs with RailsAll Things Open
1.4K views58 slides
2011 a grape odyssey by
2011   a grape odyssey2011   a grape odyssey
2011 a grape odysseyMike Hagedorn
938 views47 slides
Building web framework with Rack by
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
3.6K views63 slides
Pourquoi ruby et rails déchirent by
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentNicolas Ledez
307 views50 slides

Similar to Building RESTful APIs w/ Grape(20)

Rails web api 开发 by shaokun
Rails web api 开发Rails web api 开发
Rails web api 开发
shaokun1.3K views
FOXX - a Javascript application framework on top of ArangoDB by ArangoDB Database
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
ArangoDB Database35.8K views
Building Better Web APIs with Rails by All Things Open
Building Better Web APIs with RailsBuilding Better Web APIs with Rails
Building Better Web APIs with Rails
All Things Open1.4K views
Building web framework with Rack by sickill
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
sickill3.6K views
Pourquoi ruby et rails déchirent by Nicolas Ledez
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirent
Nicolas Ledez307 views
Serverless - Developers.IO 2019 by Shuji Watanabe
Serverless - Developers.IO 2019Serverless - Developers.IO 2019
Serverless - Developers.IO 2019
Shuji Watanabe1.8K views
Денис Лебедев-Управление зависимостями с помощью CocoaPods by UA Mobile
Денис Лебедев-Управление зависимостями с помощью CocoaPodsДенис Лебедев-Управление зависимостями с помощью CocoaPods
Денис Лебедев-Управление зависимостями с помощью CocoaPods
UA Mobile727 views
From Ruby to Node.js by jubilem
From Ruby to Node.jsFrom Ruby to Node.js
From Ruby to Node.js
jubilem1K views
Making a small QA system with Docker by Naoki AINOYA
Making a small QA system with DockerMaking a small QA system with Docker
Making a small QA system with Docker
Naoki AINOYA1.9K views
Be a microservices hero by OpenRestyCon
Be a microservices heroBe a microservices hero
Be a microservices hero
OpenRestyCon399 views
Scaling up development of a modular code base by Robert Munteanu
Scaling up development of a modular code baseScaling up development of a modular code base
Scaling up development of a modular code base
Robert Munteanu345 views
Ionic Framework - get up and running to build hybrid mobile apps by Andreas Sahle
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
Andreas Sahle1.2K views
From Zero to Mongo, Art.sy Experience w/ MongoDB by Daniel Doubrovkine
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
Daniel Doubrovkine1.5K views
Infrastructure-as-code: bridging the gap between Devs and Ops by Mykyta Protsenko
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
Mykyta Protsenko182 views
Battle of NoSQL stars: Amazon's SDB vs MongoDB vs CouchDB vs RavenDB by Jesse Wolgamott
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
Jesse Wolgamott9.7K views
High quality ap is with api platform by Nelson Kopliku
High quality ap is with api platformHigh quality ap is with api platform
High quality ap is with api platform
Nelson Kopliku1.1K views
Rails 3: Dashing to the Finish by Yehuda Katz
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
Yehuda Katz29.1K views

More from Daniel Doubrovkine

The Future of Art @ Worlds Fair Nano by
The Future of Art @ Worlds Fair NanoThe Future of Art @ Worlds Fair Nano
The Future of Art @ Worlds Fair NanoDaniel Doubrovkine
457 views52 slides
Nasdaq CTO Summit: Inspiring Team Leads to Give Away Legos by
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
573 views20 slides
Product Development 101 by
Product Development 101Product Development 101
Product Development 101Daniel Doubrovkine
785 views20 slides
Open-Source by Default, UN Community.camp by
Open-Source by Default, UN Community.campOpen-Source by Default, UN Community.camp
Open-Source by Default, UN Community.campDaniel Doubrovkine
692 views55 slides
Your First Slack Ruby Bot by
Your First Slack Ruby BotYour First Slack Ruby Bot
Your First Slack Ruby BotDaniel Doubrovkine
1.1K views12 slides
Single Sign-On with Waffle by
Single Sign-On with WaffleSingle Sign-On with Waffle
Single Sign-On with WaffleDaniel Doubrovkine
3.8K views11 slides

More from Daniel Doubrovkine(20)

Nasdaq CTO Summit: Inspiring Team Leads to Give Away Legos by Daniel Doubrovkine
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
Daniel Doubrovkine573 views
Taking Over Open Source Projects @ GoGaRuCo 2014 by Daniel Doubrovkine
Taking Over Open Source Projects @ GoGaRuCo 2014Taking Over Open Source Projects @ GoGaRuCo 2014
Taking Over Open Source Projects @ GoGaRuCo 2014
Daniel Doubrovkine1.6K views
GeneralAssemb.ly Summer Program: Tech from the Ground Up by Daniel Doubrovkine
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
Daniel Doubrovkine530 views

Recently uploaded

Roadmap to Become Experts.pptx by
Roadmap to Become Experts.pptxRoadmap to Become Experts.pptx
Roadmap to Become Experts.pptxdscwidyatamanew
11 views45 slides
ChatGPT and AI for Web Developers by
ChatGPT and AI for Web DevelopersChatGPT and AI for Web Developers
ChatGPT and AI for Web DevelopersMaximiliano Firtman
181 views82 slides
How the World's Leading Independent Automotive Distributor is Reinventing Its... by
How the World's Leading Independent Automotive Distributor is Reinventing Its...How the World's Leading Independent Automotive Distributor is Reinventing Its...
How the World's Leading Independent Automotive Distributor is Reinventing Its...NUS-ISS
15 views25 slides
Melek BEN MAHMOUD.pdf by
Melek BEN MAHMOUD.pdfMelek BEN MAHMOUD.pdf
Melek BEN MAHMOUD.pdfMelekBenMahmoud
14 views1 slide
Understanding GenAI/LLM and What is Google Offering - Felix Goh by
Understanding GenAI/LLM and What is Google Offering - Felix GohUnderstanding GenAI/LLM and What is Google Offering - Felix Goh
Understanding GenAI/LLM and What is Google Offering - Felix GohNUS-ISS
41 views33 slides
Report 2030 Digital Decade by
Report 2030 Digital DecadeReport 2030 Digital Decade
Report 2030 Digital DecadeMassimo Talia
14 views41 slides

Recently uploaded(20)

How the World's Leading Independent Automotive Distributor is Reinventing Its... by NUS-ISS
How the World's Leading Independent Automotive Distributor is Reinventing Its...How the World's Leading Independent Automotive Distributor is Reinventing Its...
How the World's Leading Independent Automotive Distributor is Reinventing Its...
NUS-ISS15 views
Understanding GenAI/LLM and What is Google Offering - Felix Goh by NUS-ISS
Understanding GenAI/LLM and What is Google Offering - Felix GohUnderstanding GenAI/LLM and What is Google Offering - Felix Goh
Understanding GenAI/LLM and What is Google Offering - Felix Goh
NUS-ISS41 views
Attacking IoT Devices from a Web Perspective - Linux Day by Simone Onofri
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day
Simone Onofri15 views
AI: mind, matter, meaning, metaphors, being, becoming, life values by Twain Liu 刘秋艳
AI: mind, matter, meaning, metaphors, being, becoming, life valuesAI: mind, matter, meaning, metaphors, being, becoming, life values
AI: mind, matter, meaning, metaphors, being, becoming, life values
[2023] Putting the R! in R&D.pdf by Eleanor McHugh
[2023] Putting the R! in R&D.pdf[2023] Putting the R! in R&D.pdf
[2023] Putting the R! in R&D.pdf
Eleanor McHugh38 views
Five Things You SHOULD Know About Postman by Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman27 views
Business Analyst Series 2023 - Week 3 Session 5 by DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10209 views
DALI Basics Course 2023 by Ivory Egg
DALI Basics Course  2023DALI Basics Course  2023
DALI Basics Course 2023
Ivory Egg14 views
Special_edition_innovator_2023.pdf by WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2216 views
handbook for web 3 adoption.pdf by Liveplex
handbook for web 3 adoption.pdfhandbook for web 3 adoption.pdf
handbook for web 3 adoption.pdf
Liveplex19 views
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV by Splunk
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV
Splunk88 views
Web Dev - 1 PPT.pdf by gdsczhcet
Web Dev - 1 PPT.pdfWeb Dev - 1 PPT.pdf
Web Dev - 1 PPT.pdf
gdsczhcet55 views
Black and White Modern Science Presentation.pptx by maryamkhalid2916
Black and White Modern Science Presentation.pptxBlack and White Modern Science Presentation.pptx
Black and White Modern Science Presentation.pptx
maryamkhalid291614 views
Voice Logger - Telephony Integration Solution at Aegis by Nirmal Sharma
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at Aegis
Nirmal Sharma17 views

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