SlideShare a Scribd company logo
1 of 44
Download to read offline
RESTful best practices
    Jean-Baptiste Escoyez & Nicolas Jacobeus

      FOSDEM ’08 Ruby on Rails DevRoom
             24 February 2008




                                          Frailers.net
Outline


REST
REST in Rails
REST in Rails: Best practices
REST
REST


       What is REST?
       How does REST work?
       Why REST?


REST
What is REST?


              It’s about communication between
              computers
              It’s about designing the architecture of
              your applications



REST » What is REST?
It’s about communication
          between computers


              Web services!
                  SOAP / XML-RPC => communication

                  REST => communication + standardisation




REST » What is REST?
It’s about architecturing
             your application
              esis by Roy Fielding (2000)
                  “Architectural Styles and the Design of Network-based
                  Software Architectures”

              REST applies some constraints to the
              architecture of your application
              e interface is the same for humans and
              computers
                       (by the way: REST means Representational State Transfer... I think)‫‏‬


REST » What is REST?
How does REST work ?


             Everything is a “resource”
             4 basic requirements for a RESTful
             system



REST » How does REST work?
e concept of resource

             Resource = thing exposed by the system to the
             outside world

             Everything is a resource
                 http://www.frailers.net/users/1
                 http://www.frailers.net/users/1/memberships

             Independent from its representation
                 user.html => http://www.frailers.net/users/1
                 user.jpg => http://www.frailers.net/users/1



REST » How does REST work?
When is a system
                    RESTful ?
             Addressability

             Statelessness

             Connectivity

             Uniform interface
                 4 standardized actions: GET - POST - PUT - DELETE

                 Safety (GET)

                 Idempotence (PUT-DELETE)

REST » How does REST work?
So, why REST ?

             Standardisation is good

             Why use so many different functions when you
             always do the same (CRUD’ing objects)

             Why separate the logic for computers and
             humans ? (segregation is evil)

             Statelessness => scalability and decoupling


REST » Why REST?
Enough for this theoretical
          HTTP stuff!



             is is a DevRoom about   , right ?




REST » Why REST?
REST in Rails




  (Not on Rails !)
REST in Rails

                Addressability: RESTful routes

                Representation independence: respond_to

                Nesting resources

                Developing REST clients

                ...and some tasty Rails sugars


REST in Rails
Addressability : Routes

                 RESTless                      RESTful
              VERB      HREF               VERB        URI
               POST      /users/create      POST    /users

                GET      /users/1           GET     /users/1

               POST      /users/1/update    PUT     /users/1

               ????      /users/1/delete   DELETE   /users/1




REST in Rails » Routes
Addressability : Routes

                           map.resources :users
              Resource            Verb            Action
                 /users            GET             index
                 /users            POST           create
                /users/1           GET             show
                /users/1           PUT            update
                /users/1          DELETE          destroy




REST in Rails » Routes
RESTful Rails controller




               A RESTful controller has 7 standard actions

               Each controller deals with a resource (user) and its
               collection (list of users)


REST in Rails » Routes
Representation independence:
        respond_to


               Based on:
                   HTTP Accept Header

                   Format extension
                       http://www.frailers.net/articles/24/comments/1.html
                       http://www.frailers.net/articles/24/comments/1.js


REST in Rails » respond_to
Making REST clients :
               ActiveResource

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

      projects = Project.find(:all)
      new_project = Project.new(:name => “My new
                                project”)
      new_project.save




REST in Rails » ActiveResource
Nested resources
                http://www.frailers.net/articles/24/comments/1
                http://www.frailers.net/articles/24/author


    ActionController::Routing::Routes.draw do |map|
      map.resources :articles do |article|
        article.resources :comments
        article.resource :author
      end
    end




REST in Rails » Nested resources
More rails sugars

               Scaffolding
               script/generate scaffold article title:string 
                               body:text published:boolean

               Helpers
                    link_to @article
                    form_for @comment do |f| ... end
                    redirect_to @article

               Authentication
                 RESTful authentication plugin

REST in Rails » Sugars
To sum up...

               Using REST in Rails is good

                   lightweight controllers

                   API given for free

               Rails is opinionated

                   implementation of REST is not perfect


REST in Rails » Conclusion
Best practices
Best practices


                 Design methodology
                 Real-life examples



Best Practices
Disclaimer!


                Maybe “best” is an overstatement
                (is sounded great for the call for papers)


                ere are always different solutions




Best Practices » Disclaimer
Design methodology


               Knowing Rails’ resources API is great, but not
               sufficient

               e big question:

                     what resources do I choose ?


Best Practices » Design methodology
Classic beginner’s
                       mistakes

               strictly mirroring your ActiveRecord data
               model to choose your resources

               thinking all 7 actions should be written for each
               and every resource

               and, of course, adding custom methods if the
               standard ones don’t fit


Best Practices » Design methodology
Resources are not
                        models

               Well, to be fair, then can (and usually)
               represent models
               But also:
                   Relations
                   States
                   Events
                   (DHH told me so)



Best Practices » Design methodology
Nouns are the new verbs
             Change your way of explaining a scenario, an action

                 Use a noun to describe the action

                 e noun given to your scenario is the resource
                 you’re looking for

             A user subscribes to a group            A subscription is created

         e project is validated by its owner     A project validation is created

           e user deactivates his account      A user account activation is deleted



Best Practices » Design methodology
7 is not a strict target

          Resources can be read-only

          Sometimes, actions are
          meaningless:
              update an “account activation” ? really ?

              destroy a “page view” ? why ?




Best Practices » Design methodology
Don’t be tempted!

               Rails allows extra, custom methods to be added to
               controllers, if you really need them

                   But you’ll lose all what you were trying to do in
                   the first place (no uniform interface, etc.)

                   I have never needed that (except, maybe...)

               If you do need that, it’s probable that you’d better
               rethink your architecture

Best Practices » Design methodology
OK, you want real-life
                    examples

                Adding/removing members from a group

                Dealing with object workflows

                Multi-step edition wizard

                Managing a shopping cart

                Manipulating several resource in one request


Best Practices » Real-life examples
Adding / Removing
            members from a group




Best Practices » Real-life examples
Adding / Removing
            members from a group




Best Practices » Real-life examples
Dealing with object
                      workflows

                Consider a CMS with
                all sorts of documents

                Each document has a
                status: draft, reviewed,
                published, ...



Best Practices » Real-life examples
Dealing with object
                      workflows




                Or another way : only “update” the document
                    depending on the business logic, this can be considered overloading


Best Practices » Real-life examples
Multi-step edition
                         wizard


            A complex model needs to
            be edited in 3 steps, in a
            precise order




Best Practices » Real-life examples
Multi-step edition
                         wizard

                All these steps are different, partial
                representations of the same resource

                Just GET the resource and put the step as a
                parameter

                Update the resource at each step... and redirect to
                the next step representation


Best Practices » Real-life examples
Multi-step edition
                         wizard




Best Practices » Real-life examples
Managing a shopping
                      cart



                We keep in the database the state of the shopping
                cart for each user:
                /users/21/shopping_cart_items


                Yes, but I don’t want the cart to be persistent
                    Delete from the database when the user logs out

Best Practices » Real-life examples
Manipulating two resources
         simultaneously

                You’re not manipulating two resources

                You’re manipulating a couple of things

                e resource is the couple

                Create guy, create girl => Create couple


Best Practices » Real-life examples
Manipulating two resources
         simultaneously
                If you still need to do it in
                several steps...

                    CREATE a Transaction resource

                    PUT the first part

                    PUT the second part

                    commit (PUT “committed”)
                    or revert (DELETE)

Best Practices » Real-life examples
ere are still some
                    limitations...

                I want to choose items to delete from a list with
                checkboxes

                DELETE only works for a single resource at a time

                What you’re doing is updating the parent resource

                    If there’s no parent resource, you’re screwed



Best Practices » Real-life examples
ank you!


              It’s lunch time!
                  Let’s eat!
                  Let’s create some LunchEatings !


POST /lunch_eatings

More Related Content

Viewers also liked

OMA Strategy on Open API Standardization
OMA Strategy on Open API StandardizationOMA Strategy on Open API Standardization
OMA Strategy on Open API StandardizationMusa Unmehopa
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Dharma Kshetri
 
RESTful Web Apps - Facts vs Fiction
RESTful Web Apps - Facts vs FictionRESTful Web Apps - Facts vs Fiction
RESTful Web Apps - Facts vs FictionSubbu Allamaraju
 
Building a RESTful API on Heroku for Your Force.com App
Building a RESTful API on Heroku for Your Force.com AppBuilding a RESTful API on Heroku for Your Force.com App
Building a RESTful API on Heroku for Your Force.com AppSalesforce Developers
 
Best practices in business writing and communication
Best practices in business writing and communicationBest practices in business writing and communication
Best practices in business writing and communicationSandra Parker
 
Rest with java (jax rs) and jersey and swagger
Rest with java (jax rs) and jersey and swaggerRest with java (jax rs) and jersey and swagger
Rest with java (jax rs) and jersey and swaggerKumaraswamy M
 
SOA & APIs: Fearless Lessons from the Field
 SOA & APIs: Fearless Lessons from the Field SOA & APIs: Fearless Lessons from the Field
SOA & APIs: Fearless Lessons from the FieldCA API Management
 
Standardizing Our Drivers Through Specifications: A Look at the CRUD API
Standardizing Our Drivers Through Specifications: A Look at the CRUD APIStandardizing Our Drivers Through Specifications: A Look at the CRUD API
Standardizing Our Drivers Through Specifications: A Look at the CRUD APIMongoDB
 
From CRUD to Hypermedia APIs with Spring
From CRUD to Hypermedia APIs with SpringFrom CRUD to Hypermedia APIs with Spring
From CRUD to Hypermedia APIs with SpringVladimir Tsukur
 
10 Steps to Effective Business Writing
10 Steps to Effective Business Writing10 Steps to Effective Business Writing
10 Steps to Effective Business WritingLenora Gan
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web servicesnbuddharaju
 
Pentesting RESTful webservices
Pentesting RESTful webservicesPentesting RESTful webservices
Pentesting RESTful webservicesMohammed A. Imran
 
rest without put
rest without putrest without put
rest without putXiaojun REN
 

Viewers also liked (16)

OMA Strategy on Open API Standardization
OMA Strategy on Open API StandardizationOMA Strategy on Open API Standardization
OMA Strategy on Open API Standardization
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 
RESTful Web Apps - Facts vs Fiction
RESTful Web Apps - Facts vs FictionRESTful Web Apps - Facts vs Fiction
RESTful Web Apps - Facts vs Fiction
 
Pragmatic Rest
Pragmatic RestPragmatic Rest
Pragmatic Rest
 
Building a RESTful API on Heroku for Your Force.com App
Building a RESTful API on Heroku for Your Force.com AppBuilding a RESTful API on Heroku for Your Force.com App
Building a RESTful API on Heroku for Your Force.com App
 
Best practices in business writing and communication
Best practices in business writing and communicationBest practices in business writing and communication
Best practices in business writing and communication
 
Rest with java (jax rs) and jersey and swagger
Rest with java (jax rs) and jersey and swaggerRest with java (jax rs) and jersey and swagger
Rest with java (jax rs) and jersey and swagger
 
SOA & APIs: Fearless Lessons from the Field
 SOA & APIs: Fearless Lessons from the Field SOA & APIs: Fearless Lessons from the Field
SOA & APIs: Fearless Lessons from the Field
 
Standardizing Our Drivers Through Specifications: A Look at the CRUD API
Standardizing Our Drivers Through Specifications: A Look at the CRUD APIStandardizing Our Drivers Through Specifications: A Look at the CRUD API
Standardizing Our Drivers Through Specifications: A Look at the CRUD API
 
Rest Vs Soap Yawn2289
Rest Vs Soap Yawn2289Rest Vs Soap Yawn2289
Rest Vs Soap Yawn2289
 
From CRUD to Hypermedia APIs with Spring
From CRUD to Hypermedia APIs with SpringFrom CRUD to Hypermedia APIs with Spring
From CRUD to Hypermedia APIs with Spring
 
10 Steps to Effective Business Writing
10 Steps to Effective Business Writing10 Steps to Effective Business Writing
10 Steps to Effective Business Writing
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
Pentesting RESTful webservices
Pentesting RESTful webservicesPentesting RESTful webservices
Pentesting RESTful webservices
 
Cqrs api v2
Cqrs api v2Cqrs api v2
Cqrs api v2
 
rest without put
rest without putrest without put
rest without put
 

Recently uploaded

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 

Recently uploaded (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

RESTful best practices

  • 1. RESTful best practices Jean-Baptiste Escoyez & Nicolas Jacobeus FOSDEM ’08 Ruby on Rails DevRoom 24 February 2008 Frailers.net
  • 2. Outline REST REST in Rails REST in Rails: Best practices
  • 4. REST What is REST? How does REST work? Why REST? REST
  • 5. What is REST? It’s about communication between computers It’s about designing the architecture of your applications REST » What is REST?
  • 6. It’s about communication between computers Web services! SOAP / XML-RPC => communication REST => communication + standardisation REST » What is REST?
  • 7. It’s about architecturing your application esis by Roy Fielding (2000) “Architectural Styles and the Design of Network-based Software Architectures” REST applies some constraints to the architecture of your application e interface is the same for humans and computers (by the way: REST means Representational State Transfer... I think)‫‏‬ REST » What is REST?
  • 8. How does REST work ? Everything is a “resource” 4 basic requirements for a RESTful system REST » How does REST work?
  • 9. e concept of resource Resource = thing exposed by the system to the outside world Everything is a resource http://www.frailers.net/users/1 http://www.frailers.net/users/1/memberships Independent from its representation user.html => http://www.frailers.net/users/1 user.jpg => http://www.frailers.net/users/1 REST » How does REST work?
  • 10. When is a system RESTful ? Addressability Statelessness Connectivity Uniform interface 4 standardized actions: GET - POST - PUT - DELETE Safety (GET) Idempotence (PUT-DELETE) REST » How does REST work?
  • 11. So, why REST ? Standardisation is good Why use so many different functions when you always do the same (CRUD’ing objects) Why separate the logic for computers and humans ? (segregation is evil) Statelessness => scalability and decoupling REST » Why REST?
  • 12. Enough for this theoretical HTTP stuff! is is a DevRoom about , right ? REST » Why REST?
  • 13. REST in Rails (Not on Rails !)
  • 14. REST in Rails Addressability: RESTful routes Representation independence: respond_to Nesting resources Developing REST clients ...and some tasty Rails sugars REST in Rails
  • 15. Addressability : Routes RESTless RESTful VERB HREF VERB URI POST /users/create POST /users GET /users/1 GET /users/1 POST /users/1/update PUT /users/1 ???? /users/1/delete DELETE /users/1 REST in Rails » Routes
  • 16. Addressability : Routes map.resources :users Resource Verb Action /users GET index /users POST create /users/1 GET show /users/1 PUT update /users/1 DELETE destroy REST in Rails » Routes
  • 17. RESTful Rails controller A RESTful controller has 7 standard actions Each controller deals with a resource (user) and its collection (list of users) REST in Rails » Routes
  • 18. Representation independence: respond_to Based on: HTTP Accept Header Format extension http://www.frailers.net/articles/24/comments/1.html http://www.frailers.net/articles/24/comments/1.js REST in Rails » respond_to
  • 19. Making REST clients : ActiveResource class Project < ActiveResource::Base self.site = “http://localhost:3000” end projects = Project.find(:all) new_project = Project.new(:name => “My new project”) new_project.save REST in Rails » ActiveResource
  • 20. Nested resources http://www.frailers.net/articles/24/comments/1 http://www.frailers.net/articles/24/author ActionController::Routing::Routes.draw do |map| map.resources :articles do |article| article.resources :comments article.resource :author end end REST in Rails » Nested resources
  • 21. More rails sugars Scaffolding script/generate scaffold article title:string body:text published:boolean Helpers link_to @article form_for @comment do |f| ... end redirect_to @article Authentication RESTful authentication plugin REST in Rails » Sugars
  • 22. To sum up... Using REST in Rails is good lightweight controllers API given for free Rails is opinionated implementation of REST is not perfect REST in Rails » Conclusion
  • 24. Best practices Design methodology Real-life examples Best Practices
  • 25. Disclaimer! Maybe “best” is an overstatement (is sounded great for the call for papers) ere are always different solutions Best Practices » Disclaimer
  • 26. Design methodology Knowing Rails’ resources API is great, but not sufficient e big question: what resources do I choose ? Best Practices » Design methodology
  • 27. Classic beginner’s mistakes strictly mirroring your ActiveRecord data model to choose your resources thinking all 7 actions should be written for each and every resource and, of course, adding custom methods if the standard ones don’t fit Best Practices » Design methodology
  • 28. Resources are not models Well, to be fair, then can (and usually) represent models But also: Relations States Events (DHH told me so) Best Practices » Design methodology
  • 29. Nouns are the new verbs Change your way of explaining a scenario, an action Use a noun to describe the action e noun given to your scenario is the resource you’re looking for A user subscribes to a group A subscription is created e project is validated by its owner A project validation is created e user deactivates his account A user account activation is deleted Best Practices » Design methodology
  • 30. 7 is not a strict target Resources can be read-only Sometimes, actions are meaningless: update an “account activation” ? really ? destroy a “page view” ? why ? Best Practices » Design methodology
  • 31. Don’t be tempted! Rails allows extra, custom methods to be added to controllers, if you really need them But you’ll lose all what you were trying to do in the first place (no uniform interface, etc.) I have never needed that (except, maybe...) If you do need that, it’s probable that you’d better rethink your architecture Best Practices » Design methodology
  • 32. OK, you want real-life examples Adding/removing members from a group Dealing with object workflows Multi-step edition wizard Managing a shopping cart Manipulating several resource in one request Best Practices » Real-life examples
  • 33. Adding / Removing members from a group Best Practices » Real-life examples
  • 34. Adding / Removing members from a group Best Practices » Real-life examples
  • 35. Dealing with object workflows Consider a CMS with all sorts of documents Each document has a status: draft, reviewed, published, ... Best Practices » Real-life examples
  • 36. Dealing with object workflows Or another way : only “update” the document depending on the business logic, this can be considered overloading Best Practices » Real-life examples
  • 37. Multi-step edition wizard A complex model needs to be edited in 3 steps, in a precise order Best Practices » Real-life examples
  • 38. Multi-step edition wizard All these steps are different, partial representations of the same resource Just GET the resource and put the step as a parameter Update the resource at each step... and redirect to the next step representation Best Practices » Real-life examples
  • 39. Multi-step edition wizard Best Practices » Real-life examples
  • 40. Managing a shopping cart We keep in the database the state of the shopping cart for each user: /users/21/shopping_cart_items Yes, but I don’t want the cart to be persistent Delete from the database when the user logs out Best Practices » Real-life examples
  • 41. Manipulating two resources simultaneously You’re not manipulating two resources You’re manipulating a couple of things e resource is the couple Create guy, create girl => Create couple Best Practices » Real-life examples
  • 42. Manipulating two resources simultaneously If you still need to do it in several steps... CREATE a Transaction resource PUT the first part PUT the second part commit (PUT “committed”) or revert (DELETE) Best Practices » Real-life examples
  • 43. ere are still some limitations... I want to choose items to delete from a list with checkboxes DELETE only works for a single resource at a time What you’re doing is updating the parent resource If there’s no parent resource, you’re screwed Best Practices » Real-life examples
  • 44. ank you! It’s lunch time! Let’s eat! Let’s create some LunchEatings ! POST /lunch_eatings