SlideShare una empresa de Scribd logo
1 de 23
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Similar a 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
 

Similar a 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
 

Último

Último (20)

What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
The UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, OcadoThe UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, Ocado
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 

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