SlideShare a Scribd company logo
REST And railsChhorn ChamnapYoolkMango15 - July - 2010
AgendaREST TheoryRESTful RailsCase StudyAuthenticationReferences
REST Theory
REST IntroductionREST is a unifying theory for how “distributed hypermedia” systems are best organized and structured.Lesson learnt from developers:CRUD operations correspond to HTTP POST, GET, PUT, and DELETE.Consistent, robust, and understandable.Names identifies resources
ResourcesA resource is something with identity.a row in adatabase, a physical object, an abstract concept, or a real-world event in progressA resource has a URI. Possible to have more than one???Different representations of a resource vary based on their content types.How does the server know which one to send?URI extensions (/users/1.html,/users/1.xml)Content negotiation (Accept-Language, Accept-Charset, Accept-Encoding, or Accept)
Resources (example)GET /orders/124 HTTP/1.1	Host: www.example.com	Accept: text/html, application/xhtml+xml, text/*, image/png, image/*, */*
Embrace hyperlinks Use hyperlinks to related resources. Provide a reasonable quantity of information and link to further details.
StatelessnessREST is stateless.It presents scalibility.Each request carries no state at lower or higher levels.Resource statethe internal state that all non trivial resources carry, and it is essential to a web application.Application state (session state)the state of the cli-ent’s interaction with the serverkeeping this state on the server violates REST principles as it breaks addressability.
HTTP Verbs (HTTP Methods)Verbs correspond to actions on resources.GETHEADPOSTPUTDELETE
Safe MethodsSafe methods are used for retrieval.never be to perform an updateAll safe methods are idempotent.
Idempotent MethodsGET, HEAD, PUT, and DELETE are idempotent methods.The response (and resource state) is the same, no matter how many times thataction is performed.
HTTP Status CodesSuccess and failure should be inferred from the HTTP response statusnot from an error message within the payload.1xx: Informational2xx: Success3xx: Redirection4xx: Client Error5xx: Server Error
GET MethodTransfers a representation of a resource to the client.Read-only access to a resource.The server must decide to perform an update based on a safe request.
PUT MethodUpdates a resource with the representation provided in the body.If not exist before, the request creates a new one.
DELETE MethodDeletes the resource identified by its URI.Subsequent GET queries to the same URI should return a status code of 410 (Gone) or 404 (Not Found).
POST MethodNeither safe nor idempotentTwo primary uses:creation of new objectsannotation of existing objectsThe URI of the POST is that of the object’s container or parent.The Location header should point to the URI of the created resource
RESTful Rails
Resource-Based Named RoutesEncapsulates all of the Rails CRUD actions into one routing statementmap.resources :users
Custom resource routescreate custom named routes either to the collection (the parent resource) or the members of the collection (the children).map.resources :people, :collection => { :search => :get }, :member => { :deactivate => :post }
Nested routesmap.resources :people do |person|	person.resources :friendsend/people/1/friends/people/1/friends/2map.resources :people do |person|	person.resources :friends, :name_prefix => 'person_'endThe name _prefix option adds a prefix to the generated routes.person_friends_path and person_friend_path
Nested routes (cont.)map.resources :peoplemap.resources :friends,		:name_prefix => 'person_',		:path_prefix => '/people/:person_id‘path_prefix option will add a prefix to the URIs that the route will recognize and generate.
Singleton resource routesSometimes, there will be an entity that exists as a singleton.map.resources :users do |user|	user.resource :accountendThe resource name is still singular, but the inferred controller name is plural.
ActionView SupportThe link_to family of helpers can take a :method parameter to define the HTTP method.generate hidden form field for the _method parameter for PUT and DELETE.<%= link_to 'Delete', person_path(@person), :method => :delete %>
Content TypesRails has introduced rich support for rendering different responses based on the content type the client wants, via the respond_to method.respond_to do |format|	format.html #format.html { render }	format.xml { render :xml => @product }endrespond_to :html, :xmlIn config/initializers/mime_types.rbMime::Type.register "image/jpeg", :jpg, [], %w(jpeg)
Content Types (cont.)
Content Types (cont.)
Resourceful session stateAlternative to holding session state on the server?Nearly any problem REST developers face, the solution is to model it as a resource.
Case Study
Example
Rest and Rails
Rest and Rails
Refactor
Refactor (example)
Refactor (example)
Rest and Rails
Authentication
AuthenticationCan we used cookies?Yes, cookies can be used, but mainly for authentication.How to authenticate users in a RESTful way via the browser and other clients?
Authentication (cont.)Use cookies/sessions to store information just for authentication.Use HTTP Basic authentication for other server side clients.For more secure, use secure http.
Authentication (cont.)
Authentication (cont.)
ReferencesAdvanced Rails RecipesOReilly Advanced RailsOreilly RESTful Web Serviceshttp://ajaxpatterns.org/RESTful_Service

More Related Content

What's hot (20)

PDF
Restful Web Services
Angelin R
 
PPT
REST Presentation
Alexandros Marinos
 
PPTX
Overview of RESTful web services
nbuddharaju
 
PPTX
JSON and REST
Robert MacLean
 
PPTX
REST & RESTful Web Services
Halil Burak Cetinkaya
 
PDF
Representational State Transfer (REST)
David Krmpotic
 
PDF
REST - Representational State Transfer
Peter R. Egli
 
PDF
RESTful Web Services with Spring MVC
digitalsonic
 
PPTX
RESTful Architecture
Kabir Baidya
 
PDF
HATEOAS: The Confusing Bit from REST
elliando dias
 
PPTX
Restful web services ppt
OECLIB Odisha Electronics Control Library
 
PDF
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
elliando dias
 
PDF
Basic web architecture
Ralu Mihordea
 
PDF
Representational State Transfer (REST) and HATEOAS
Guy K. Kloss
 
PDF
REST - Representational state transfer
Tricode (part of Dept)
 
PPTX
Best practices for RESTful web service design
Ramin Orujov
 
PPT
RESTful services
gouthamrv
 
PDF
Intoduction to php web services and json
baabtra.com - No. 1 supplier of quality freshers
 
PDF
REST, RESTful API
Hossein Baghayi
 
PPT
External Data Access with jQuery
Doncho Minkov
 
Restful Web Services
Angelin R
 
REST Presentation
Alexandros Marinos
 
Overview of RESTful web services
nbuddharaju
 
JSON and REST
Robert MacLean
 
REST & RESTful Web Services
Halil Burak Cetinkaya
 
Representational State Transfer (REST)
David Krmpotic
 
REST - Representational State Transfer
Peter R. Egli
 
RESTful Web Services with Spring MVC
digitalsonic
 
RESTful Architecture
Kabir Baidya
 
HATEOAS: The Confusing Bit from REST
elliando dias
 
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
elliando dias
 
Basic web architecture
Ralu Mihordea
 
Representational State Transfer (REST) and HATEOAS
Guy K. Kloss
 
REST - Representational state transfer
Tricode (part of Dept)
 
Best practices for RESTful web service design
Ramin Orujov
 
RESTful services
gouthamrv
 
Intoduction to php web services and json
baabtra.com - No. 1 supplier of quality freshers
 
REST, RESTful API
Hossein Baghayi
 
External Data Access with jQuery
Doncho Minkov
 

Viewers also liked (11)

PDF
Ruby on Rails 101
Clayton Lengel-Zigich
 
PDF
Rails Text Mate Cheats
dezarrolla
 
KEY
Rails 3 generators
joshsmoore
 
PDF
Rails01
Al Sayed Gamal
 
PDF
Ruby on Rails Kickstart 103 & 104
Heng-Yi Wu
 
KEY
Ruby on Rails Training - Module 1
Mark Menard
 
PDF
Railsguide
lanlau
 
KEY
Introducing Command Line Applications with Ruby
Nikhil Mungel
 
PDF
Rails 3 Beginner to Builder 2011 Week 3
Richard Schneeman
 
PDF
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
peter_marklund
 
PDF
Ruby on Rails for beginners
Vysakh Sreenivasan
 
Ruby on Rails 101
Clayton Lengel-Zigich
 
Rails Text Mate Cheats
dezarrolla
 
Rails 3 generators
joshsmoore
 
Ruby on Rails Kickstart 103 & 104
Heng-Yi Wu
 
Ruby on Rails Training - Module 1
Mark Menard
 
Railsguide
lanlau
 
Introducing Command Line Applications with Ruby
Nikhil Mungel
 
Rails 3 Beginner to Builder 2011 Week 3
Richard Schneeman
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
peter_marklund
 
Ruby on Rails for beginners
Vysakh Sreenivasan
 
Ad

Similar to Rest and Rails (20)

PDF
Rest And Rails
Kaushik Jha
 
PDF
Restful Best Practices
Belighted
 
PPTX
A Deep Dive into RESTful API Design Part 2
VivekKrishna34
 
PDF
REST Basics
Ivano Malavolta
 
PPT
RESTful SOA - 中科院暑期讲座
Li Yi
 
PDF
Rest Introduction (Chris Jimenez)
PiXeL16
 
PDF
RESTful Web Services
Christopher Bartling
 
PPTX
RESTful for opentravel.org by HP
Roni Schuetz
 
PDF
Designing Res Tful Rails Applications
ConSanFrancisco123
 
PPSX
Restful web services rule financial
Rule_Financial
 
KEY
Routes Controllers
Blazing Cloud
 
PDF
OpenTravel Advisory Forum 2012 REST XML Resources
OpenTravel Alliance
 
PDF
Consuming REST services with ActiveResource
Wolfram Arnold
 
ODP
RESTful Web Services with JAX-RS
Carol McDonald
 
PDF
Finding Restfulness - Madrid.rb April 2014
samlown
 
PDF
Rest
Ivano Malavolta
 
PDF
RESTful web
Alvin Qi
 
KEY
20120121 rbc rails_routing
Takeshi AKIMA
 
PPTX
Learning to code for startup mvp session 3
Henry S
 
PDF
What is REST?
Saeid Zebardast
 
Rest And Rails
Kaushik Jha
 
Restful Best Practices
Belighted
 
A Deep Dive into RESTful API Design Part 2
VivekKrishna34
 
REST Basics
Ivano Malavolta
 
RESTful SOA - 中科院暑期讲座
Li Yi
 
Rest Introduction (Chris Jimenez)
PiXeL16
 
RESTful Web Services
Christopher Bartling
 
RESTful for opentravel.org by HP
Roni Schuetz
 
Designing Res Tful Rails Applications
ConSanFrancisco123
 
Restful web services rule financial
Rule_Financial
 
Routes Controllers
Blazing Cloud
 
OpenTravel Advisory Forum 2012 REST XML Resources
OpenTravel Alliance
 
Consuming REST services with ActiveResource
Wolfram Arnold
 
RESTful Web Services with JAX-RS
Carol McDonald
 
Finding Restfulness - Madrid.rb April 2014
samlown
 
RESTful web
Alvin Qi
 
20120121 rbc rails_routing
Takeshi AKIMA
 
Learning to code for startup mvp session 3
Henry S
 
What is REST?
Saeid Zebardast
 
Ad

More from Chamnap Chhorn (6)

PDF
Introduction to rails
Chamnap Chhorn
 
PDF
High performance website
Chamnap Chhorn
 
PPTX
Ruby object model
Chamnap Chhorn
 
PPTX
Introduction to Web Architecture
Chamnap Chhorn
 
PPT
Principles in Refactoring
Chamnap Chhorn
 
PPTX
JavaScript in Object-Oriented Way
Chamnap Chhorn
 
Introduction to rails
Chamnap Chhorn
 
High performance website
Chamnap Chhorn
 
Ruby object model
Chamnap Chhorn
 
Introduction to Web Architecture
Chamnap Chhorn
 
Principles in Refactoring
Chamnap Chhorn
 
JavaScript in Object-Oriented Way
Chamnap Chhorn
 

Recently uploaded (20)

DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Biography of Daniel Podor.pdf
Daniel Podor
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 

Rest and Rails

  • 1. REST And railsChhorn ChamnapYoolkMango15 - July - 2010
  • 2. AgendaREST TheoryRESTful RailsCase StudyAuthenticationReferences
  • 4. REST IntroductionREST is a unifying theory for how “distributed hypermedia” systems are best organized and structured.Lesson learnt from developers:CRUD operations correspond to HTTP POST, GET, PUT, and DELETE.Consistent, robust, and understandable.Names identifies resources
  • 5. ResourcesA resource is something with identity.a row in adatabase, a physical object, an abstract concept, or a real-world event in progressA resource has a URI. Possible to have more than one???Different representations of a resource vary based on their content types.How does the server know which one to send?URI extensions (/users/1.html,/users/1.xml)Content negotiation (Accept-Language, Accept-Charset, Accept-Encoding, or Accept)
  • 6. Resources (example)GET /orders/124 HTTP/1.1 Host: www.example.com Accept: text/html, application/xhtml+xml, text/*, image/png, image/*, */*
  • 7. Embrace hyperlinks Use hyperlinks to related resources. Provide a reasonable quantity of information and link to further details.
  • 8. StatelessnessREST is stateless.It presents scalibility.Each request carries no state at lower or higher levels.Resource statethe internal state that all non trivial resources carry, and it is essential to a web application.Application state (session state)the state of the cli-ent’s interaction with the serverkeeping this state on the server violates REST principles as it breaks addressability.
  • 9. HTTP Verbs (HTTP Methods)Verbs correspond to actions on resources.GETHEADPOSTPUTDELETE
  • 10. Safe MethodsSafe methods are used for retrieval.never be to perform an updateAll safe methods are idempotent.
  • 11. Idempotent MethodsGET, HEAD, PUT, and DELETE are idempotent methods.The response (and resource state) is the same, no matter how many times thataction is performed.
  • 12. HTTP Status CodesSuccess and failure should be inferred from the HTTP response statusnot from an error message within the payload.1xx: Informational2xx: Success3xx: Redirection4xx: Client Error5xx: Server Error
  • 13. GET MethodTransfers a representation of a resource to the client.Read-only access to a resource.The server must decide to perform an update based on a safe request.
  • 14. PUT MethodUpdates a resource with the representation provided in the body.If not exist before, the request creates a new one.
  • 15. DELETE MethodDeletes the resource identified by its URI.Subsequent GET queries to the same URI should return a status code of 410 (Gone) or 404 (Not Found).
  • 16. POST MethodNeither safe nor idempotentTwo primary uses:creation of new objectsannotation of existing objectsThe URI of the POST is that of the object’s container or parent.The Location header should point to the URI of the created resource
  • 18. Resource-Based Named RoutesEncapsulates all of the Rails CRUD actions into one routing statementmap.resources :users
  • 19. Custom resource routescreate custom named routes either to the collection (the parent resource) or the members of the collection (the children).map.resources :people, :collection => { :search => :get }, :member => { :deactivate => :post }
  • 20. Nested routesmap.resources :people do |person| person.resources :friendsend/people/1/friends/people/1/friends/2map.resources :people do |person| person.resources :friends, :name_prefix => 'person_'endThe name _prefix option adds a prefix to the generated routes.person_friends_path and person_friend_path
  • 21. Nested routes (cont.)map.resources :peoplemap.resources :friends, :name_prefix => 'person_', :path_prefix => '/people/:person_id‘path_prefix option will add a prefix to the URIs that the route will recognize and generate.
  • 22. Singleton resource routesSometimes, there will be an entity that exists as a singleton.map.resources :users do |user| user.resource :accountendThe resource name is still singular, but the inferred controller name is plural.
  • 23. ActionView SupportThe link_to family of helpers can take a :method parameter to define the HTTP method.generate hidden form field for the _method parameter for PUT and DELETE.<%= link_to 'Delete', person_path(@person), :method => :delete %>
  • 24. Content TypesRails has introduced rich support for rendering different responses based on the content type the client wants, via the respond_to method.respond_to do |format| format.html #format.html { render } format.xml { render :xml => @product }endrespond_to :html, :xmlIn config/initializers/mime_types.rbMime::Type.register "image/jpeg", :jpg, [], %w(jpeg)
  • 27. Resourceful session stateAlternative to holding session state on the server?Nearly any problem REST developers face, the solution is to model it as a resource.
  • 37. AuthenticationCan we used cookies?Yes, cookies can be used, but mainly for authentication.How to authenticate users in a RESTful way via the browser and other clients?
  • 38. Authentication (cont.)Use cookies/sessions to store information just for authentication.Use HTTP Basic authentication for other server side clients.For more secure, use secure http.
  • 41. ReferencesAdvanced Rails RecipesOReilly Advanced RailsOreilly RESTful Web Serviceshttp://ajaxpatterns.org/RESTful_Service