SlideShare ist ein Scribd-Unternehmen logo
1 von 65
How Restful is Your Rest?
       Abdelmonaim Remani
        @PolymathicCoder




          Øredev 2012
         Malmö, Sweden
License




Creative Commons Attribution Non-Commercial 3.0 Unported
   http://creativecommons.org/licenses/by-nc/3.0


Disclaimer: The graphics, logos, and trademarks used this presentation
belong to their rightful owners.
Trevligt att träffa dig nordisk
           hackare!
About Me

Software Architect at Just.me Inc.
Interested in technology evangelism and enterprise software
development and architecture
Frequent speaker (JavaOne, JAX, OSCON, OREDEV, etc…)
Open-source advocate
President and founder of a number of user groups
  NorCal Java User Group
  The Silicon Valley Spring User Group
  The Silicon Valley Dart Meetup
Bio:       http://about.me/PolymathicCoder
Twitter:   @PolymathicCoder
Email:     abdelmonaim.remani@gmail.com
Let’s Get Started!
What is an API?


Application Programming Interface
You have an API when
  (All or a part of) the functionality of your system is exposed
  In the form a well-defined interface (or a collection of interfaces)
  of services
     That are externally accessible
     And programmatically consumable through to a well-defined protocol
You have a Web API when
  The functionality of your system is exposed
  In the form of a collection of Web Services
     That are publicly addressable through a set of Web endpoints (URLs)
     And programmatically consumable though HTTP protocol
Why Bother?


Web 2.0
  Convenience and standardization around accessing data and
  services
Explosion of Open APIs
  Location-Based (Maps, Geo-coding, Weather, Traffic, Etc…)
  Financial Data
  Social Data
  Government Data, NGOs, etc…
  Etc…
Why Bother?


The birth of Mashups (Hybrid Web Applications)
  Combines services to create a value-added
  Aggregate and visualize data in interesting ways
Spoiled user-base that demands a lot more than what
a single service can offer
  I want to see the closest Moroccan restaurants to my
  current location on a map along with consumer ratings
  and whether any of my friends has recently checked-in
  in the last 30 days
Why Bother?


Mobile
  A lot more apps than browsers
  Mobile traffic is diminishing web traffic exponentially
Mashups 2.0 is Mobile
Why Bother?


You goal behind exposing a Web API should be for your
services to be mashed up with others
  Beneficial
    Will drive traffic in your direction
    Will allow you to learn about your own services and how they
    are being used
    Will create goodwill with new potential users
Implies
  The majority of the traffic is NOT going to be through your
  own app or website
  Your App is the API it exposes
Challenges


You have very little control on how your API will be
used
  You do not control how your services are orchestrated
  (Used in combination)
Public APIs are forever
  Better get it right the first time!
What’s Right?


How does a good API feel like?
  Easy to learn and use
    Intuitive
      POLA (Principle of Least Astonishment)
    Consistent
      Based on standards
      Adheres to a convention
  Hard to misuse
  Well-Documented
What is REST?
What is REST?


REpresentational State Transfer
Roy Fielding Dissertation (Chapter 5-6)
  Architectural Styles and the Design of Network-based
  Software Architectures
  http://www.ics.uci.edu/~fielding/pubs/dissertation/top.h
  tm
What is REST about?


Goals
  Scalability
  Generality of Interface
  Independent Deployment of Component
  Intermediary Components
Rest Constraints
  Client-Server
  Stateless Conversion
  Cacheable
  Uniform Interface
  Layered System
  Code on-demand (Optional)
What is REST about?


Leveraging the web as a platform
  Resource-Oriented
    Anything exposed on the web is a resource
    (Documents, video, device, etc…)
    Resources are identifiable and addressable by URIs
An architecture based on the HTTP protocol
API Design
Richardson Maturity Model


Leonard Richardson
  http://www.crummy.com/writing/speaking/2008-Qcon/
The Address Book
The Address Book


A Simple address book that allows users to manage their contact data
A user has a username and is associated with a set of contacts
A contact is constitute of: a unique ID, a name, and a phone number
User Stories:
  As a user, I want to add a contact to my address book
  As a user, I want to list all contacts in my address book
  As a user, I want to view a specific contact in my address book
  As a user, I want to modify a specific contact in my address book
  As a user, I want to delete a specific contact from my address book
  As a user, I want to email a specific contact in my address book to a friend
Richardson Maturity Model
            Level 0


Single URI
  Identify all possible operations/functionality
  indicate the desired operation in the payload
Single HTTP Verb
The Address Book at Level 0


SOAP-Based RPC Web Service
  Endpoint
    http://www.polymathiccoder.com:9999/ws/addressbook
  WSDL
    http://www. polymathiccoder.com:9999/ws/addressbook?wsdl
  addContact(“bob”, “Abdel Remani”, “(123) 123-1234”)
  lookupAllContacts(“bob”)
  lookupContactById(“bob”, 123)
  editContact(“bob”, 123, “Abdelmonaim Remani”, “(123) 123-
  1234”)
  deleteContact(“bob”, 123)
  emailContact(“bob”, 123, “sandy@polymathiccoder.com”)
  markAsFavorite(“bob”, 123)
Richardson Maturity Model
            Level 1


Multiple URLs
  One URL per method
  URI encoded operations
Single Verb
  GET is used to change stage
  GET should be safe or idempotent
The Address Book at Level 1

URL Tunneling
  Endpoints
    http://www. polymathiccoder.com/addressbook/add-
    contact?user=bob&name=Abdel%20Remani&phone-
    number=(123)%20123-1234
    http://www. polymathiccoder.com/addressbook/lookup-all-
    contacts?user=bob
    http://www. polymathiccoder.com/addressbook/lookup-
    contact?user=bob&id=123
    http://www. polymathiccoder.com/addressbook/edit-
    contact?user=bob&id=123&name=Abdelmonaim%20Remani&phone-
    number=(123)%20123-1234
    http://www. polymathiccoder.com/addressbook/delete-
    contact?user=bob&id=123
    http://www.
    polymathiccoder.com/addressbook/email?user=bob&id=123&to=sand
    y@polymathiccoder.com
    http://www. polymathiccoder.com/addressbook/mark-as-
Richardson Maturity Model
            Level 2


Level 2
  Many URI
  Leverage multiple HTTP Verbs
You might call yourself Restful at this point
  Creating a uniform interface based on the HTTP protocol
The Address Book at Level 2
    The Restful Address Book
Recourse Identification


Find all the nouns in users stories
Recourse Identification


Here are all the nouns we found:
  User
    Uniquely identifiable by a username
  Contact
    Uniquely identifiable by an id
Let’s start calling nouns resources
Recourse Identification


Resources are identifiable and addressable by URIs
  The collection of resources the same kind
    Users
       /users
    Contacts
       /contacts
  The individual resources within its collections
    The User whose username is “abdel”
       /users/abdel
    The Contact whose ID is “123”
       /contacts/123
Recourse Identification


Is there association between any of our resources?
  User has many Contacts
  A User can is the parent resource of a Contact
Chaining resources together
  “/” in a URI implies hierarchy
  Contact whose id is “123” and owner is the User whose
  username is “abdel”
    /users/abdel/contacts/123
Recourse Identification


We end with 2 URIs referring to the same Contact
resource whose ID is “123”
  /contcats/123
  /users/abdel/contacts/123
We ask the question: Can a “Contact” recourse exist
independently from “User” resource?
  The Answer is NO in this case
  /contcats/123
  /users/abdel/contacts/123
Leveraging HTTP Verbs


User Stories:
Leveraging HTTP Verbs


CRUD Operations map to HTTP Verbs
  GET for Read
  POST for Create
  PUT for Update
  DELETE for Delete
Leveraging HTTP Verbs


To view all Abdel’s contacts
  GET      /users/abdel/contacts
To view Abdel’s contact whose ID is 123
  GET      /users/abdel/contacts/123
To add a new contact to Abdel’s address book
  POST     /users/abdel/contacts
To update Abdel’s contact whose is ID is 123
  PUT     /users/abdel/contacts/123
To delete Abdel’s contact whose is ID is 123
  DELETE /users/abdel/contacts/123
Non-CRUD


Non-CRUD operations do not map to HTTP verbs
  Use descriptive verbs in URLs as Controller calls
To email Abdel’s contact whose ID is 123 to
sandy@polymathiccoder.com
  GET
  /users/abdel/contacts/123/email?to=sandy@polymathicc
  oder.com
To mark Abdel’s contact whose ID is 123 to
sandy@polymathiccoder.com
  PUT /users/abdel/contacts/123/mark-as-favorite
The Opinion Shop: URLs


Convention for your URLs
  RFC 3986: URLs are case sensitive
    No CAPS to avoid confusion
    No camel-case
  Links are usually underlined
    Use Hyphens instead of Underscores for readability
Resource Representation


For a resource identified by the same URI
  Representation in the form of MIME/Media Types
  Multiple data representation is supported
    Use “Accept” HTTP Header
    Avoid file extensions
  Manipulation is supported through multiple data
  representation
    Use “Content-Type” HTTP Header
The Opinion Shop: URLs


Convention object names in payload
    No JavaScript Convention
      http://javascript.crockford.com/code.html
      No camel-case
    I prefer using using Hyphens to be consistent with URLs
Leveraging HTTP Status Codes


1xx: Informational
2xx: Success
3xx: Redirection
4xx: Client Error
5xx: Server Error
Leveraging HTTP Status Codes


200 – OK
   Success
   Error with details in the body
201 – Created
202 – Accepted
400 – Bad Request
401 – Unauthorized
403 – Forbidden
404 – Not Found
405 – Method Not Allowed
406 – Not Acceptable
409 – Conflict
412 – Precondition Failed
415 – Unsupported Media Type
500 – Server Problems
Richardson Maturity Model
            Level 4


HATEOAS
  Hypermedia As The Engine Of Application Sate
Business Workflow
  Capturing the different states of a resource
  Transitions Endpoint
Returning all possible links given the current state of
the resource
Partials and Variations
Pagination


Use Query Parameters
Pagination
  Don’t do this
    /page/1
  Inspired by SQL
    ?limit=20&offset=20
  Inspired by RFC 5005: Feed Paging and Archiving
    http://tools.ietf.org/html/rfc5005
    ?next=20&to-item=6783&inclusive=true
    ?prev=23&to-item=6783&inclusive=false
Ordering, Sorting and Fitering


Use Query Parameters
Ordering and Sorting
  ?order-by=populatrity&sorted-as=desc
  ?order-by=first-name&sorted-as=asc
Filtering
  ?filter-by=
  Etc…
Views


Support custom views of the data at the schema level
  Use an easy expression language
    ?fields=(first-name,phone-number)
    ?fields=!(last-name)
  Google, LinkedIn, and others use a variations
Support different predefined views of the data
  Use
    ?view=brief
    ?view=full
Legacy Clients
Legacy Clients


Older Clients
  Only support GET and POST HTTP Methods
Use
  ?method=put
Security
Security


Remember that your Web Services must be stateless
  Do not use cookies or HTTP session under any circumstances
  The client must send credentials to autenticate with very call
Options
  HTTP Security
    Preemptively Setting “Authorization” HTTP Header
    Basic or Digest
  OAuth
Testing You API
Testing

Spring RestTemplate
  http://static.springsource.org/spring/docs/3.1.x/spring-
  framework-reference/html/remoting.html#rest-
  resttemplate
Jayway’s Rest-Assured
  http://code.google.com/p/rest-assured/
Versioning
Versioning


Don’t do this
  /api/v1/…
  ?v=1
  /api/v1.1/…
  /api/07-19-2012/…
Use HTTP Headers
  Use Vendor-Specific MIME/Media Types
  Accept
    application/vnd.polymathiccoder.addressbook+json
Documentation
Documentation


What to document
  Endpoint
  Description
  Prerequisites
  Request
  Response
Documentation




What to document
 Use a mind map
Documentation


Refer to other’s documentations
  Twitter, Facebook, Google, etc…
ioDocs from Mashery
  http://www.mashery.com/product/io-docs
  Live Example:
    http://developer.rottentomatoes.com/iodocs
How Restful Is REST?
How Restful Is Your REST?


Richardson Maturity Model as a reference
  It’ll tell where you stand
How Restful do you want to be?
Dogmatic vs. Pragmatic
In Common Law, there is this concept of “The Reasonable
Man”
  Being reasonable is relative
  Look in similar situation
  Similar expertise
  Custom and usage
Question?
Recommended Reading
Tack själv!
PolymathicCoder

Weitere ähnliche Inhalte

Was ist angesagt?

SharePoint 2010, Claims-Based Identity, Facebook, and the Cloud
SharePoint 2010, Claims-Based Identity, Facebook, and the CloudSharePoint 2010, Claims-Based Identity, Facebook, and the Cloud
SharePoint 2010, Claims-Based Identity, Facebook, and the CloudDanny Jessee
 
Advanced applications-architecture-threats
Advanced applications-architecture-threatsAdvanced applications-architecture-threats
Advanced applications-architecture-threatsBlueinfy Solutions
 
Assessment methodology and approach
Assessment methodology and approachAssessment methodology and approach
Assessment methodology and approachBlueinfy Solutions
 
Hacking Ajax & Web Services - Next Generation Web Attacks on the Rise
Hacking Ajax & Web Services - Next Generation Web Attacks on the RiseHacking Ajax & Web Services - Next Generation Web Attacks on the Rise
Hacking Ajax & Web Services - Next Generation Web Attacks on the RiseShreeraj Shah
 
Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast trackBinu Bhasuran
 
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]Shreeraj Shah
 
Web Attacks - Top threats - 2010
Web Attacks - Top threats - 2010Web Attacks - Top threats - 2010
Web Attacks - Top threats - 2010Shreeraj Shah
 
Web 2.0 Application Kung-Fu - Securing Ajax & Web Services
Web 2.0 Application Kung-Fu - Securing Ajax & Web ServicesWeb 2.0 Application Kung-Fu - Securing Ajax & Web Services
Web 2.0 Application Kung-Fu - Securing Ajax & Web ServicesShreeraj Shah
 
Innovate2011 Keys to Building OSLC Integrations
Innovate2011 Keys to Building OSLC IntegrationsInnovate2011 Keys to Building OSLC Integrations
Innovate2011 Keys to Building OSLC IntegrationsSteve Speicher
 
Authorization in asp
Authorization in aspAuthorization in asp
Authorization in aspOPENLANE
 
Net course content
Net course contentNet course content
Net course contentmindq
 
XSS and CSRF with HTML5
XSS and CSRF with HTML5XSS and CSRF with HTML5
XSS and CSRF with HTML5Shreeraj Shah
 
[Infosecworld 08 Orlando] CSRF: The Biggest Little Vulnerability on the Web
[Infosecworld 08 Orlando] CSRF: The Biggest Little Vulnerability on the Web [Infosecworld 08 Orlando] CSRF: The Biggest Little Vulnerability on the Web
[Infosecworld 08 Orlando] CSRF: The Biggest Little Vulnerability on the Web Shreeraj Shah
 

Was ist angesagt? (20)

SharePoint 2010, Claims-Based Identity, Facebook, and the Cloud
SharePoint 2010, Claims-Based Identity, Facebook, and the CloudSharePoint 2010, Claims-Based Identity, Facebook, and the Cloud
SharePoint 2010, Claims-Based Identity, Facebook, and the Cloud
 
Advanced applications-architecture-threats
Advanced applications-architecture-threatsAdvanced applications-architecture-threats
Advanced applications-architecture-threats
 
Application fuzzing
Application fuzzingApplication fuzzing
Application fuzzing
 
Owasp web security
Owasp web securityOwasp web security
Owasp web security
 
Assessment methodology and approach
Assessment methodology and approachAssessment methodology and approach
Assessment methodology and approach
 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
 
Hacking Ajax & Web Services - Next Generation Web Attacks on the Rise
Hacking Ajax & Web Services - Next Generation Web Attacks on the RiseHacking Ajax & Web Services - Next Generation Web Attacks on the Rise
Hacking Ajax & Web Services - Next Generation Web Attacks on the Rise
 
Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast track
 
RESTful Day 5
RESTful Day 5RESTful Day 5
RESTful Day 5
 
ReSTful API Final
ReSTful API FinalReSTful API Final
ReSTful API Final
 
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
Hacking Web 2.0 - Defending Ajax and Web Services [HITB 2007 Dubai]
 
Overview of JEE Technology
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE Technology
 
Web Attacks - Top threats - 2010
Web Attacks - Top threats - 2010Web Attacks - Top threats - 2010
Web Attacks - Top threats - 2010
 
Web 2.0 Application Kung-Fu - Securing Ajax & Web Services
Web 2.0 Application Kung-Fu - Securing Ajax & Web ServicesWeb 2.0 Application Kung-Fu - Securing Ajax & Web Services
Web 2.0 Application Kung-Fu - Securing Ajax & Web Services
 
Innovate2011 Keys to Building OSLC Integrations
Innovate2011 Keys to Building OSLC IntegrationsInnovate2011 Keys to Building OSLC Integrations
Innovate2011 Keys to Building OSLC Integrations
 
Authorization in asp
Authorization in aspAuthorization in asp
Authorization in asp
 
Net course content
Net course contentNet course content
Net course content
 
XSS and CSRF with HTML5
XSS and CSRF with HTML5XSS and CSRF with HTML5
XSS and CSRF with HTML5
 
[Infosecworld 08 Orlando] CSRF: The Biggest Little Vulnerability on the Web
[Infosecworld 08 Orlando] CSRF: The Biggest Little Vulnerability on the Web [Infosecworld 08 Orlando] CSRF: The Biggest Little Vulnerability on the Web
[Infosecworld 08 Orlando] CSRF: The Biggest Little Vulnerability on the Web
 
Hibernate I
Hibernate IHibernate I
Hibernate I
 

Andere mochten auch

The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java Abdelmonaim Remani
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding RESTNitin Pande
 
ReST (Representational State Transfer) Explained
ReST (Representational State Transfer) ExplainedReST (Representational State Transfer) Explained
ReST (Representational State Transfer) ExplainedDhananjay Nene
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsStormpath
 

Andere mochten auch (7)

Why HATEOAS
Why HATEOASWhy HATEOAS
Why HATEOAS
 
The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 
RESTful API Design, Second Edition
RESTful API Design, Second EditionRESTful API Design, Second Edition
RESTful API Design, Second Edition
 
ReST (Representational State Transfer) Explained
ReST (Representational State Transfer) ExplainedReST (Representational State Transfer) Explained
ReST (Representational State Transfer) Explained
 
EVOLVE'13 | Keynote | Roy Fielding
EVOLVE'13 | Keynote | Roy FieldingEVOLVE'13 | Keynote | Roy Fielding
EVOLVE'13 | Keynote | Roy Fielding
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
 

Ähnlich wie How RESTful Is Your REST?

Restful web-services
Restful web-servicesRestful web-services
Restful web-servicesrporwal
 
Fundamentals of Web Development For Non-Developers
Fundamentals of Web Development For Non-DevelopersFundamentals of Web Development For Non-Developers
Fundamentals of Web Development For Non-DevelopersLemi Orhan Ergin
 
Introduction to API
Introduction to APIIntroduction to API
Introduction to APIrajnishjha29
 
How APIs Can Be Secured in Mobile Environments
How APIs Can Be Secured in Mobile EnvironmentsHow APIs Can Be Secured in Mobile Environments
How APIs Can Be Secured in Mobile EnvironmentsWSO2
 
Web services soap and rest by mandakini for TechGig
Web services soap and rest by mandakini for TechGigWeb services soap and rest by mandakini for TechGig
Web services soap and rest by mandakini for TechGigMandakini Kumari
 
Separating REST Facts from Fallacies
Separating REST Facts from FallaciesSeparating REST Facts from Fallacies
Separating REST Facts from FallaciesAlan Dean
 
Web2 0 Incredibles
Web2 0 IncrediblesWeb2 0 Incredibles
Web2 0 Incrediblesanjeshdubey
 
Service-Finder presentation at ESTC2008
Service-Finder presentation at ESTC2008Service-Finder presentation at ESTC2008
Service-Finder presentation at ESTC2008servicefinder
 
Realizing Service Finder at ESTC 2008
Realizing Service Finder at ESTC 2008Realizing Service Finder at ESTC 2008
Realizing Service Finder at ESTC 2008Emanuele Della Valle
 
Best practices and advantages of REST APIs
Best practices and advantages of REST APIsBest practices and advantages of REST APIs
Best practices and advantages of REST APIsAparna Sharma
 

Ähnlich wie How RESTful Is Your REST? (20)

Modified REST Presentation
Modified REST PresentationModified REST Presentation
Modified REST Presentation
 
REST Presentation
REST PresentationREST Presentation
REST Presentation
 
Restful web-services
Restful web-servicesRestful web-services
Restful web-services
 
Fundamentals of Web Development For Non-Developers
Fundamentals of Web Development For Non-DevelopersFundamentals of Web Development For Non-Developers
Fundamentals of Web Development For Non-Developers
 
Introduction to API
Introduction to APIIntroduction to API
Introduction to API
 
How APIs Can Be Secured in Mobile Environments
How APIs Can Be Secured in Mobile EnvironmentsHow APIs Can Be Secured in Mobile Environments
How APIs Can Be Secured in Mobile Environments
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Web services soap and rest by mandakini for TechGig
Web services soap and rest by mandakini for TechGigWeb services soap and rest by mandakini for TechGig
Web services soap and rest by mandakini for TechGig
 
Rest web service
Rest web serviceRest web service
Rest web service
 
WebApp #3 : API
WebApp #3 : APIWebApp #3 : API
WebApp #3 : API
 
Separating REST Facts from Fallacies
Separating REST Facts from FallaciesSeparating REST Facts from Fallacies
Separating REST Facts from Fallacies
 
Treinamento 1
Treinamento 1Treinamento 1
Treinamento 1
 
Web2 0 Incredibles
Web2 0 IncrediblesWeb2 0 Incredibles
Web2 0 Incredibles
 
Restful api
Restful apiRestful api
Restful api
 
Introduction to Hydra
Introduction to HydraIntroduction to Hydra
Introduction to Hydra
 
REST full API Design
REST full API DesignREST full API Design
REST full API Design
 
SFDC REST API
SFDC REST APISFDC REST API
SFDC REST API
 
Service-Finder presentation at ESTC2008
Service-Finder presentation at ESTC2008Service-Finder presentation at ESTC2008
Service-Finder presentation at ESTC2008
 
Realizing Service Finder at ESTC 2008
Realizing Service Finder at ESTC 2008Realizing Service Finder at ESTC 2008
Realizing Service Finder at ESTC 2008
 
Best practices and advantages of REST APIs
Best practices and advantages of REST APIsBest practices and advantages of REST APIs
Best practices and advantages of REST APIs
 

Mehr von Abdelmonaim Remani

The Economies of Scaling Software
The Economies of Scaling SoftwareThe Economies of Scaling Software
The Economies of Scaling SoftwareAbdelmonaim Remani
 
The Rise of NoSQL and Polyglot Persistence
The Rise of NoSQL and Polyglot PersistenceThe Rise of NoSQL and Polyglot Persistence
The Rise of NoSQL and Polyglot PersistenceAbdelmonaim Remani
 
Introduction To Building Enterprise Web Application With Spring Mvc
Introduction To Building Enterprise Web Application With Spring MvcIntroduction To Building Enterprise Web Application With Spring Mvc
Introduction To Building Enterprise Web Application With Spring MvcAbdelmonaim Remani
 
Introduction To Rich Internet Applications
Introduction To Rich Internet ApplicationsIntroduction To Rich Internet Applications
Introduction To Rich Internet ApplicationsAbdelmonaim Remani
 

Mehr von Abdelmonaim Remani (6)

The Eschatology of Java
The Eschatology of JavaThe Eschatology of Java
The Eschatology of Java
 
The Economies of Scaling Software
The Economies of Scaling SoftwareThe Economies of Scaling Software
The Economies of Scaling Software
 
The Rise of NoSQL and Polyglot Persistence
The Rise of NoSQL and Polyglot PersistenceThe Rise of NoSQL and Polyglot Persistence
The Rise of NoSQL and Polyglot Persistence
 
Le Tour de xUnit
Le Tour de xUnitLe Tour de xUnit
Le Tour de xUnit
 
Introduction To Building Enterprise Web Application With Spring Mvc
Introduction To Building Enterprise Web Application With Spring MvcIntroduction To Building Enterprise Web Application With Spring Mvc
Introduction To Building Enterprise Web Application With Spring Mvc
 
Introduction To Rich Internet Applications
Introduction To Rich Internet ApplicationsIntroduction To Rich Internet Applications
Introduction To Rich Internet Applications
 

Kürzlich hochgeladen

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 

Kürzlich hochgeladen (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

How RESTful Is Your REST?

  • 1. How Restful is Your Rest? Abdelmonaim Remani @PolymathicCoder Øredev 2012 Malmö, Sweden
  • 2. License Creative Commons Attribution Non-Commercial 3.0 Unported http://creativecommons.org/licenses/by-nc/3.0 Disclaimer: The graphics, logos, and trademarks used this presentation belong to their rightful owners.
  • 3. Trevligt att träffa dig nordisk hackare!
  • 4. About Me Software Architect at Just.me Inc. Interested in technology evangelism and enterprise software development and architecture Frequent speaker (JavaOne, JAX, OSCON, OREDEV, etc…) Open-source advocate President and founder of a number of user groups NorCal Java User Group The Silicon Valley Spring User Group The Silicon Valley Dart Meetup Bio: http://about.me/PolymathicCoder Twitter: @PolymathicCoder Email: abdelmonaim.remani@gmail.com
  • 6. What is an API? Application Programming Interface You have an API when (All or a part of) the functionality of your system is exposed In the form a well-defined interface (or a collection of interfaces) of services That are externally accessible And programmatically consumable through to a well-defined protocol You have a Web API when The functionality of your system is exposed In the form of a collection of Web Services That are publicly addressable through a set of Web endpoints (URLs) And programmatically consumable though HTTP protocol
  • 7. Why Bother? Web 2.0 Convenience and standardization around accessing data and services Explosion of Open APIs Location-Based (Maps, Geo-coding, Weather, Traffic, Etc…) Financial Data Social Data Government Data, NGOs, etc… Etc…
  • 8. Why Bother? The birth of Mashups (Hybrid Web Applications) Combines services to create a value-added Aggregate and visualize data in interesting ways Spoiled user-base that demands a lot more than what a single service can offer I want to see the closest Moroccan restaurants to my current location on a map along with consumer ratings and whether any of my friends has recently checked-in in the last 30 days
  • 9. Why Bother? Mobile A lot more apps than browsers Mobile traffic is diminishing web traffic exponentially Mashups 2.0 is Mobile
  • 10. Why Bother? You goal behind exposing a Web API should be for your services to be mashed up with others Beneficial Will drive traffic in your direction Will allow you to learn about your own services and how they are being used Will create goodwill with new potential users Implies The majority of the traffic is NOT going to be through your own app or website Your App is the API it exposes
  • 11. Challenges You have very little control on how your API will be used You do not control how your services are orchestrated (Used in combination) Public APIs are forever Better get it right the first time!
  • 12. What’s Right? How does a good API feel like? Easy to learn and use Intuitive POLA (Principle of Least Astonishment) Consistent Based on standards Adheres to a convention Hard to misuse Well-Documented
  • 14. What is REST? REpresentational State Transfer Roy Fielding Dissertation (Chapter 5-6) Architectural Styles and the Design of Network-based Software Architectures http://www.ics.uci.edu/~fielding/pubs/dissertation/top.h tm
  • 15. What is REST about? Goals Scalability Generality of Interface Independent Deployment of Component Intermediary Components Rest Constraints Client-Server Stateless Conversion Cacheable Uniform Interface Layered System Code on-demand (Optional)
  • 16. What is REST about? Leveraging the web as a platform Resource-Oriented Anything exposed on the web is a resource (Documents, video, device, etc…) Resources are identifiable and addressable by URIs An architecture based on the HTTP protocol
  • 18. Richardson Maturity Model Leonard Richardson http://www.crummy.com/writing/speaking/2008-Qcon/
  • 20. The Address Book A Simple address book that allows users to manage their contact data A user has a username and is associated with a set of contacts A contact is constitute of: a unique ID, a name, and a phone number User Stories: As a user, I want to add a contact to my address book As a user, I want to list all contacts in my address book As a user, I want to view a specific contact in my address book As a user, I want to modify a specific contact in my address book As a user, I want to delete a specific contact from my address book As a user, I want to email a specific contact in my address book to a friend
  • 21. Richardson Maturity Model Level 0 Single URI Identify all possible operations/functionality indicate the desired operation in the payload Single HTTP Verb
  • 22. The Address Book at Level 0 SOAP-Based RPC Web Service Endpoint http://www.polymathiccoder.com:9999/ws/addressbook WSDL http://www. polymathiccoder.com:9999/ws/addressbook?wsdl addContact(“bob”, “Abdel Remani”, “(123) 123-1234”) lookupAllContacts(“bob”) lookupContactById(“bob”, 123) editContact(“bob”, 123, “Abdelmonaim Remani”, “(123) 123- 1234”) deleteContact(“bob”, 123) emailContact(“bob”, 123, “sandy@polymathiccoder.com”) markAsFavorite(“bob”, 123)
  • 23. Richardson Maturity Model Level 1 Multiple URLs One URL per method URI encoded operations Single Verb GET is used to change stage GET should be safe or idempotent
  • 24. The Address Book at Level 1 URL Tunneling Endpoints http://www. polymathiccoder.com/addressbook/add- contact?user=bob&name=Abdel%20Remani&phone- number=(123)%20123-1234 http://www. polymathiccoder.com/addressbook/lookup-all- contacts?user=bob http://www. polymathiccoder.com/addressbook/lookup- contact?user=bob&id=123 http://www. polymathiccoder.com/addressbook/edit- contact?user=bob&id=123&name=Abdelmonaim%20Remani&phone- number=(123)%20123-1234 http://www. polymathiccoder.com/addressbook/delete- contact?user=bob&id=123 http://www. polymathiccoder.com/addressbook/email?user=bob&id=123&to=sand y@polymathiccoder.com http://www. polymathiccoder.com/addressbook/mark-as-
  • 25. Richardson Maturity Model Level 2 Level 2 Many URI Leverage multiple HTTP Verbs You might call yourself Restful at this point Creating a uniform interface based on the HTTP protocol
  • 26. The Address Book at Level 2 The Restful Address Book
  • 27. Recourse Identification Find all the nouns in users stories
  • 28. Recourse Identification Here are all the nouns we found: User Uniquely identifiable by a username Contact Uniquely identifiable by an id Let’s start calling nouns resources
  • 29. Recourse Identification Resources are identifiable and addressable by URIs The collection of resources the same kind Users /users Contacts /contacts The individual resources within its collections The User whose username is “abdel” /users/abdel The Contact whose ID is “123” /contacts/123
  • 30. Recourse Identification Is there association between any of our resources? User has many Contacts A User can is the parent resource of a Contact Chaining resources together “/” in a URI implies hierarchy Contact whose id is “123” and owner is the User whose username is “abdel” /users/abdel/contacts/123
  • 31. Recourse Identification We end with 2 URIs referring to the same Contact resource whose ID is “123” /contcats/123 /users/abdel/contacts/123 We ask the question: Can a “Contact” recourse exist independently from “User” resource? The Answer is NO in this case /contcats/123 /users/abdel/contacts/123
  • 33.
  • 34. Leveraging HTTP Verbs CRUD Operations map to HTTP Verbs GET for Read POST for Create PUT for Update DELETE for Delete
  • 35. Leveraging HTTP Verbs To view all Abdel’s contacts GET /users/abdel/contacts To view Abdel’s contact whose ID is 123 GET /users/abdel/contacts/123 To add a new contact to Abdel’s address book POST /users/abdel/contacts To update Abdel’s contact whose is ID is 123 PUT /users/abdel/contacts/123 To delete Abdel’s contact whose is ID is 123 DELETE /users/abdel/contacts/123
  • 36.
  • 37. Non-CRUD Non-CRUD operations do not map to HTTP verbs Use descriptive verbs in URLs as Controller calls To email Abdel’s contact whose ID is 123 to sandy@polymathiccoder.com GET /users/abdel/contacts/123/email?to=sandy@polymathicc oder.com To mark Abdel’s contact whose ID is 123 to sandy@polymathiccoder.com PUT /users/abdel/contacts/123/mark-as-favorite
  • 38.
  • 39. The Opinion Shop: URLs Convention for your URLs RFC 3986: URLs are case sensitive No CAPS to avoid confusion No camel-case Links are usually underlined Use Hyphens instead of Underscores for readability
  • 40. Resource Representation For a resource identified by the same URI Representation in the form of MIME/Media Types Multiple data representation is supported Use “Accept” HTTP Header Avoid file extensions Manipulation is supported through multiple data representation Use “Content-Type” HTTP Header
  • 41. The Opinion Shop: URLs Convention object names in payload No JavaScript Convention http://javascript.crockford.com/code.html No camel-case I prefer using using Hyphens to be consistent with URLs
  • 42. Leveraging HTTP Status Codes 1xx: Informational 2xx: Success 3xx: Redirection 4xx: Client Error 5xx: Server Error
  • 43. Leveraging HTTP Status Codes 200 – OK Success Error with details in the body 201 – Created 202 – Accepted 400 – Bad Request 401 – Unauthorized 403 – Forbidden 404 – Not Found 405 – Method Not Allowed 406 – Not Acceptable 409 – Conflict 412 – Precondition Failed 415 – Unsupported Media Type 500 – Server Problems
  • 44. Richardson Maturity Model Level 4 HATEOAS Hypermedia As The Engine Of Application Sate Business Workflow Capturing the different states of a resource Transitions Endpoint Returning all possible links given the current state of the resource
  • 46. Pagination Use Query Parameters Pagination Don’t do this /page/1 Inspired by SQL ?limit=20&offset=20 Inspired by RFC 5005: Feed Paging and Archiving http://tools.ietf.org/html/rfc5005 ?next=20&to-item=6783&inclusive=true ?prev=23&to-item=6783&inclusive=false
  • 47. Ordering, Sorting and Fitering Use Query Parameters Ordering and Sorting ?order-by=populatrity&sorted-as=desc ?order-by=first-name&sorted-as=asc Filtering ?filter-by= Etc…
  • 48. Views Support custom views of the data at the schema level Use an easy expression language ?fields=(first-name,phone-number) ?fields=!(last-name) Google, LinkedIn, and others use a variations Support different predefined views of the data Use ?view=brief ?view=full
  • 50. Legacy Clients Older Clients Only support GET and POST HTTP Methods Use ?method=put
  • 52. Security Remember that your Web Services must be stateless Do not use cookies or HTTP session under any circumstances The client must send credentials to autenticate with very call Options HTTP Security Preemptively Setting “Authorization” HTTP Header Basic or Digest OAuth
  • 54. Testing Spring RestTemplate http://static.springsource.org/spring/docs/3.1.x/spring- framework-reference/html/remoting.html#rest- resttemplate Jayway’s Rest-Assured http://code.google.com/p/rest-assured/
  • 56. Versioning Don’t do this /api/v1/… ?v=1 /api/v1.1/… /api/07-19-2012/… Use HTTP Headers Use Vendor-Specific MIME/Media Types Accept application/vnd.polymathiccoder.addressbook+json
  • 58. Documentation What to document Endpoint Description Prerequisites Request Response
  • 60. Documentation Refer to other’s documentations Twitter, Facebook, Google, etc… ioDocs from Mashery http://www.mashery.com/product/io-docs Live Example: http://developer.rottentomatoes.com/iodocs
  • 61. How Restful Is REST?
  • 62. How Restful Is Your REST? Richardson Maturity Model as a reference It’ll tell where you stand How Restful do you want to be? Dogmatic vs. Pragmatic In Common Law, there is this concept of “The Reasonable Man” Being reasonable is relative Look in similar situation Similar expertise Custom and usage

Hinweis der Redaktion

  1. http://translate.google.com/#sv/en/Trevligt%20att%20träffa%20dig%20svenska%20hackare!http://translate.google.com/#en/sv/I%20am%20happy%20to%20be%20here