SlideShare ist ein Scribd-Unternehmen logo
1 von 23
Downloaden Sie, um offline zu lesen
Consuming REST services
  with ActiveResource

Wolfram Arnold, @wolframarnold
      www.rubyfocus.biz
ActiveResource?


            Maps

         Resources
            to
          Objects
ActiveResource

                     Server

                URL           JSON


      Client    ActiveResource


               Obj              Obj
REST?



   REpresentational
   State
   Transfer
Requests and responses are built around the
    transfer of representations of resources.

Individual resources are identified in requests, [...]
     using URIs in web-based REST systems.

                                       Source: Wikipedia
RESTful URL's Rails-style
map.resources :trips (in config/routes.rb)
      GET       /trips            → “index” action
      POST      /trips            → “create” action
      GET       /trips/new        → “new” action
      GET       /trips/:id/edit   → “edit” action with ID
      GET       /trips/:id        → “show” action with ID
      PUT       /trips/:id        → “update” action with ID
      DELETE    /trips/:id        → “destroy” action with ID
Why it's hard?
●   Opinionated
●   Poorly documented
       –   Read the sources
       –   Use an editor that makes this easy
●   Less mature than ActiveRecord
●   Trial by fire
DEMO
                            demo project:
git://github.com/wolframarnold/SFMeetup-Talk-on-ActiveResource-2011-
                               12-08.git

                                server:
       git://github.com/wolframarnold/where-have-you-been.git
                     branch: sfmeetup_2011_12_08
CRUD
Trip.find(:all)                 → GET /trips.json
Trip.find(1)                    → GET /trips/1.json
trip = Trip.create(name: “...”) → POST /trips.json
trip.name = “California”
trip.save                       → PUT /trips/1.json
trip.delete                     → DELETE /trips/1.json
Declaration
class Trip < ActiveResource::Base


 self.site = “http://localhost:3000”


end
Declaration
class Trip < ActiveResource::Base
 self.site = “http://localhost:3000”


 schema do
   string :name
 end


end
Schema
Schema
DateTime objects via JSON
config/initializer/active_resource.rb


ActiveSupport::JSON::Encoding.
 use_standard_json_time_format = true


ActiveSupport.parse_json_times = true
Validations
●   Local
       class Trip < ActiveResrouce::Base
            validates :name, :presence => true
       end
●   Remote
       –   Server issues 422 (“Unprocessable Entity”)
       –   trip.errors[:name] (theoretically)
       –   (Default Rails Scaffold omits “errors” key)
       –   Attribute-specific errors happen only if declared in
             schema
Nested Resources
class Comment < ActiveResource::Base
 self.prefix = "posts/:post_id/comments"
end


Comment.find(100, post_id: 200)


→ /posts/200/comments/100.json
Nested Resources != Associations
●   You don't get:
       –   post.comments
       –   comment.post
●   No Association methods
●   No validations across parent/children
RESTful Relationshiops???
●   Individual controllers, flat data structure
       –   /posts
       –   /posts/111/comments
       –   tough to enforce constraints across requests
●   Single controller, nested data structure
       –   /posts
       –   post: {comments: [ {body: “blah”} ]}
       –   lose 1:1 mapping object to resources
ActiveResource

     !=

ActiveRecord
ActiveRecord vs. ActiveResource
“AR” (ActiveRecord)         “ARes” (ActiveResource)
●   Tightly coupled to DB   ●   API's vary wide and
●   Maps relations well          far
●   SQL strictly defined
                            ●   No underlying
                                 standards
●   SQL drives
     consistency
                            ●   “REST” loosely
                                  defined
Limitations
Additional query parameters on create, update


Trip.create(name: “Canada”)


→ "trip"=>{"name"=>"canada"}
Limitations
Additional query parameters on create, update


Trip.create(name: “Canada”,
            auth_token: “mpohuZVe8dKD”)


→ "trip"=>{"name"=>"canada",
           "auth_token"=>"mpohuZVe8dKD"}
Recommendations
●   Good starting point for Rails REST servers
●   Don't pretend it's ActiveRecord
●   Informs design of API object adapters for non-
      Rails services
●   Many gems define custom API-object mapping
●   The Command Pattern

Weitere ähnliche Inhalte

Was ist angesagt?

Content-centric architectures - case study : Apache Sling
Content-centric architectures - case study : Apache SlingContent-centric architectures - case study : Apache Sling
Content-centric architectures - case study : Apache Sling
Fabrice Hong
 

Was ist angesagt? (20)

Angularjs & REST
Angularjs & RESTAngularjs & REST
Angularjs & REST
 
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
 
Apache Sling as an OSGi-powered REST middleware
Apache Sling as an OSGi-powered REST middlewareApache Sling as an OSGi-powered REST middleware
Apache Sling as an OSGi-powered REST middleware
 
RESTFul development with Apache sling
RESTFul development with Apache slingRESTFul development with Apache sling
RESTFul development with Apache sling
 
From ActiveRecord to EventSourcing
From ActiveRecord to EventSourcingFrom ActiveRecord to EventSourcing
From ActiveRecord to EventSourcing
 
The Evolution of Airbnb's Frontend
The Evolution of Airbnb's FrontendThe Evolution of Airbnb's Frontend
The Evolution of Airbnb's Frontend
 
Introduce cucumber
Introduce cucumberIntroduce cucumber
Introduce cucumber
 
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLEREST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
 
Django rest framework tips and tricks
Django rest framework   tips and tricksDjango rest framework   tips and tricks
Django rest framework tips and tricks
 
PLAT-8 Spring Web Scripts and Spring Surf
PLAT-8 Spring Web Scripts and Spring SurfPLAT-8 Spring Web Scripts and Spring Surf
PLAT-8 Spring Web Scripts and Spring Surf
 
Intro to Sails.js
Intro to Sails.jsIntro to Sails.js
Intro to Sails.js
 
REST in AngularJS
REST in AngularJSREST in AngularJS
REST in AngularJS
 
Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1
 
Using RESTFUL APIs in ANGULARJS
Using RESTFUL APIs in ANGULARJSUsing RESTFUL APIs in ANGULARJS
Using RESTFUL APIs in ANGULARJS
 
Intro to Rails and MVC
Intro to Rails and MVCIntro to Rails and MVC
Intro to Rails and MVC
 
How to connect AngularJS to servers
How to connect AngularJS to serversHow to connect AngularJS to servers
How to connect AngularJS to servers
 
Ruby On Grape
Ruby On GrapeRuby On Grape
Ruby On Grape
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to Swagger
 
Django rest framework
Django rest frameworkDjango rest framework
Django rest framework
 
Content-centric architectures - case study : Apache Sling
Content-centric architectures - case study : Apache SlingContent-centric architectures - case study : Apache Sling
Content-centric architectures - case study : Apache Sling
 

Ähnlich wie Consuming REST services with ActiveResource

20120121 rbc rails_routing
20120121 rbc rails_routing20120121 rbc rails_routing
20120121 rbc rails_routing
Takeshi AKIMA
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Tatsuhiko Miyagawa
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Solutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Solutions for bi-directional Integration between Oracle RDMBS & Apache KafkaSolutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Solutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Guido Schmutz
 
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
confluent
 
RESTful JSON web databases
RESTful JSON web databasesRESTful JSON web databases
RESTful JSON web databases
kriszyp
 

Ähnlich wie Consuming REST services with ActiveResource (20)

20120121 rbc rails_routing
20120121 rbc rails_routing20120121 rbc rails_routing
20120121 rbc rails_routing
 
Integrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationIntegrating React.js Into a PHP Application
Integrating React.js Into a PHP Application
 
Couchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problemCouchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problem
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
 
Rest And Rails
Rest And RailsRest And Rails
Rest And Rails
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
 
Headless Drupal en pratique
Headless Drupal en pratiqueHeadless Drupal en pratique
Headless Drupal en pratique
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortega
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
 
Kotlin 在 Web 方面的应用
Kotlin 在 Web 方面的应用Kotlin 在 Web 方面的应用
Kotlin 在 Web 方面的应用
 
Couchdb Nosql
Couchdb NosqlCouchdb Nosql
Couchdb Nosql
 
CouchDB : More Couch
CouchDB : More CouchCouchDB : More Couch
CouchDB : More Couch
 
Riak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup GroupRiak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup Group
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Solutions for bi-directional integration between Oracle RDBMS & Apache Kafka
Solutions for bi-directional integration between Oracle RDBMS & Apache KafkaSolutions for bi-directional integration between Oracle RDBMS & Apache Kafka
Solutions for bi-directional integration between Oracle RDBMS & Apache Kafka
 
Solutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Solutions for bi-directional Integration between Oracle RDMBS & Apache KafkaSolutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Solutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
 
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirent
 
RESTful JSON web databases
RESTful JSON web databasesRESTful JSON web databases
RESTful JSON web databases
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 

Consuming REST services with ActiveResource

  • 1. Consuming REST services with ActiveResource Wolfram Arnold, @wolframarnold www.rubyfocus.biz
  • 2. ActiveResource? Maps Resources to Objects
  • 3. ActiveResource Server URL JSON Client ActiveResource Obj Obj
  • 4. REST? REpresentational State Transfer
  • 5. Requests and responses are built around the transfer of representations of resources. Individual resources are identified in requests, [...] using URIs in web-based REST systems. Source: Wikipedia
  • 6. RESTful URL's Rails-style map.resources :trips (in config/routes.rb) GET /trips → “index” action POST /trips → “create” action GET /trips/new → “new” action GET /trips/:id/edit → “edit” action with ID GET /trips/:id → “show” action with ID PUT /trips/:id → “update” action with ID DELETE /trips/:id → “destroy” action with ID
  • 7. Why it's hard? ● Opinionated ● Poorly documented – Read the sources – Use an editor that makes this easy ● Less mature than ActiveRecord ● Trial by fire
  • 8. DEMO demo project: git://github.com/wolframarnold/SFMeetup-Talk-on-ActiveResource-2011- 12-08.git server: git://github.com/wolframarnold/where-have-you-been.git branch: sfmeetup_2011_12_08
  • 9. CRUD Trip.find(:all) → GET /trips.json Trip.find(1) → GET /trips/1.json trip = Trip.create(name: “...”) → POST /trips.json trip.name = “California” trip.save → PUT /trips/1.json trip.delete → DELETE /trips/1.json
  • 10. Declaration class Trip < ActiveResource::Base self.site = “http://localhost:3000” end
  • 11. Declaration class Trip < ActiveResource::Base self.site = “http://localhost:3000” schema do string :name end end
  • 14. DateTime objects via JSON config/initializer/active_resource.rb ActiveSupport::JSON::Encoding. use_standard_json_time_format = true ActiveSupport.parse_json_times = true
  • 15. Validations ● Local class Trip < ActiveResrouce::Base validates :name, :presence => true end ● Remote – Server issues 422 (“Unprocessable Entity”) – trip.errors[:name] (theoretically) – (Default Rails Scaffold omits “errors” key) – Attribute-specific errors happen only if declared in schema
  • 16. Nested Resources class Comment < ActiveResource::Base self.prefix = "posts/:post_id/comments" end Comment.find(100, post_id: 200) → /posts/200/comments/100.json
  • 17. Nested Resources != Associations ● You don't get: – post.comments – comment.post ● No Association methods ● No validations across parent/children
  • 18. RESTful Relationshiops??? ● Individual controllers, flat data structure – /posts – /posts/111/comments – tough to enforce constraints across requests ● Single controller, nested data structure – /posts – post: {comments: [ {body: “blah”} ]} – lose 1:1 mapping object to resources
  • 19. ActiveResource != ActiveRecord
  • 20. ActiveRecord vs. ActiveResource “AR” (ActiveRecord) “ARes” (ActiveResource) ● Tightly coupled to DB ● API's vary wide and ● Maps relations well far ● SQL strictly defined ● No underlying standards ● SQL drives consistency ● “REST” loosely defined
  • 21. Limitations Additional query parameters on create, update Trip.create(name: “Canada”) → "trip"=>{"name"=>"canada"}
  • 22. Limitations Additional query parameters on create, update Trip.create(name: “Canada”, auth_token: “mpohuZVe8dKD”) → "trip"=>{"name"=>"canada", "auth_token"=>"mpohuZVe8dKD"}
  • 23. Recommendations ● Good starting point for Rails REST servers ● Don't pretend it's ActiveRecord ● Informs design of API object adapters for non- Rails services ● Many gems define custom API-object mapping ● The Command Pattern