SlideShare a Scribd company logo
Knowledge Share
REST Methodologies
June 19, 2013
Topics
• High level on REST
• Richardson Maturity Model
•Bulk of today’s session
• Etc
•Data Formats, Caching, Versioning, Discovery, Security
• Q&A
What is REST?
• REST is an architectural constraint based on HTTP 1.1, and
created as part of Roy Fielding’s doctoral dissertation in 2000
• It embraces HTTP
• It’s not a style, not a standard
http://en.wikipedia.org/wiki/Representational_state_transfer
http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
Richardson Maturity Model
…since few REST implementators read Fielding’s thesis
• a way to grade your API according to the REST constraints.
• the better your API adheres these constraints, the higher its
score is.
• 4 levels of increasing compliance
• Level 3 designates a “truly” RESTful API
Level 0: Swamp of POX
• POX = Plain Old XML
• uses a transport protocol merely for tunneling. No properties
of the transfer protocol is used, and all work is done through
this tunnel.
• Typically uses only one entry point (URI) and one kind of
method (in HTTP, this normally is the POST method).
• Examples: SOAP and XML-RPC
Level 1: Resources
• When your API can distinguish between different resources,
it might be level 1.
• Uses multiple URIs, where every URI is the entry point to a
specific resource.
• Examples:
• /article/1 vs /article/2
• /articles
• Still, this level uses only one single method like POST
• /articles/create_new
URI Design
• Slashes – hierarchical
• /user/JROD/friends (“ah, this returns a list of JROD’s friends”)
• Hyphens or underscores – readability (preferred: hyphens)
• /notAGoodWay
• /a_better_way
• /the-preferred-way
• Query String – Filtering: ?, &, =
• Semicolons: Matrix parameters, hierarchial, categorical
 /reports/some-report/date/2009-03/sort-by/email
• Returns email? date? report?
 /reports/some-report?date=2009-03&sort-by=email
Collection Resources
• “Plurals”
• /users
• /users/JROD/friends
• Used for
• Paginated views
• Filtered views
• Create new member resources
• Friend request => POST /users/JROD/friends
• Perform same operation on multiple resources
Composite Resources
• Combines information from other resources
• Approach #1
• => GET /customer/1234
• => GET /customer/1234/orders?sort_by=date&limit=10
• => GET /customer/1234/quotes?sort_by=date&limit=10&status=pending
• Great for modular design, bad for network (chatty)
• Can we minimize network overhead without compromising REST?
• Approach #2
• => GET /customer/1234/snapshot
• <=
<snapshot><customer>..</customer><orders>..</orders><quotes>..</quotes></snaps
hot>
Modifying Multiple Resources
• Want to tackle write operations that involve modifying more
than one resource atomically?
• RESTful controllers
• If creating a single resource <= 201 Created, Location
• If modifying 1+ resources <= 303 See Other, Location
• If more than one Location <= 200 OK, Body: all Locations
• Errors
Level 2: HTTP Verbs
• indicates that your API should use the transport protocol
properties in order to deal with scalability and failures
• Don't use a single POST method for all, but make use of GET
when you are requesting resources, and use the DELETE
method when you want to delete a resources
• Use HTTP response codes properly
• Don't return 200 (OK) when something went wrong.
• Use HTTP headers properly
HTTP Verbs
• GET /user/21  retrieves a resource from a URI
• DELETE /user/21  removes the resource
• POST /users  creates a new record; returns Location
• PUT /user/21  updates a resource
PUT vs POST
• Some literature seemingly use POST or PUT interchangeably
• When do you use PUT vs POST?
• POST
• URL is decided by server
• Response: 201 Created & Location header
• If full representation in response, add Content-Location header
• PUT
• URL decided by client
• Response: 201 Created
• Preference: PUT for updates, POST for creates
Asynchronous Tasks
• Some requests take time to complete
• Creates (POST), deletes (DELETE)
• Multithreaded AJAX controllers can hang!
• How to handle?
• => POST /imgs/tasks
• <= 202 (Accepted), Content-Location: /imgs/task/1, Body: “got it!”
• => GET /imgs/task/1
• (still processing) <= 200 (OK), Body: “still processing!”
• (done) <= 303 (See Other), Location: /imgs/1, Body: “done!”
• (failed) <= 200 (OK), Body: “error reason”
• Why 200 on fail? Because task succeeded, image did not
Status Codes
Convey the result of the server’s attempt to satisfy the request
• 1xx: informational
• 2xx: success
• 3xx: redirection
• 4xx: client error
• 5xx: server error
Error Codes
• Client errors
• 400 (Bad Request) – missing required HTTP packet info
• 401 (Unauthorized) – can be fixed if authenticated
• 403 (Forbidden) – don’t try again, can’t access
• 404 (Not Found) – never existed or deleted
• 405 (Not Allowed) – HTTP method not allowed
• 406 (Not Acceptable) – Requested media type not an option
• 409 (Conflict) – “request conflicts with current state of resource”
• 412 (Precondition Failed) – See conditional requests
• 413 (Request Entity Too Large) – POST or PUT request too big,
provide limit details
• 415 (Unsupported Media Type) – Sent media type not supported
Error Codes
• Server errors
• 500 (Internal Server Error)
• Generic; “uhoh, I missed something” = bug
• 503 (Service Unavailable)
• Database connection
• Rate limit
• Best practice: include Retry-After header
• All errors
• Include message in Body (unless method = HEAD)
Headers
• Content-Type
• Prefer to use well-known media types for representations
• application/json is the de facto standard for JSON responses
• Content-Type = MIME-Type = File format ≠ Schema
• Application-specific media types
• promote visibility provided that such media types are widely supported
• In general, should be avoided as they may reduce interoperability with clients
and other tools, such as debuggers and test clients
• Last-Modified
Level 3: Hypermedia Controls
The level where most fall down. There are two parts to this:
Content negotiation
• focused on different representations of a particular resource
HATEAOS
• = Hypermedia as the Engine of Application State
• No a priori knowledge of service required
• Discoverability of actions on a resource.
• Navigation options are provided by service and hypermedia controls
• Promotes longevity through a uniform interface
HATEAOS
Links
• Provide navigation from a given resource
• Dynamic, based on resource state
<link href=“/user/232/customers” rel=“customers” />
Linking
{
“links”: *
{
“rel”: “self”
“href”: “…”
},
{
“rel”: “alternate”
“href”: “…”
}
{
“rel”: “previous”
“href”: “…”
}
}
Pagination
• What to include in collection resources
• Links to self, next (if not at end), previous (if not at start)
• Size of collection
• Example
• => GET /articles?contains=cycling&start=10
• <= Body:
• total: 1921
• self: “http://foo.com/articles?contains=cycling&start=10”
• prev: “http://foo.com/articles?contains=cycling”
• next: “http://foo.com/articles?contains=cycling&start=20”
• articles: { }
Homogeneity
• Analogous to supertypes in Java collections
• aka don’t rely on Object

• products: [ car: {id, mpg}, boat: {id, hull}]

• products: [
product: ,id, type: “car”, make, model-
boat: ,id, type: “boat”, make, model-
]
Data Formats
• Dates, times, numbers, currencies, etc.
• Choosing portable formats for human readability and avoid
interoperability errors
• Countries & states: ISO-3166: (US, CA) vs. (US-NY, CA-BC)
• Currencies: ISO 4217: USD, CAD, JPY
• Locales: RFCs 5645, 5646: en-US, en-CA, ja-JP
• Dates & times: ISO 8601/RFC 3339
• String sortable/comparable
• Human readable (else use Unix epoch)
• UTC format prevents time zone issues
• E.g., 2013-06-19T11:26:00Z-5:00
Caching
• Expiration caching in HTTP done in two ways
• Expires (HTTP 1.0)
• Cache-Control (HTTP 1.1)
• Private, public, no-store, etc.
• Pragma: no-cache (HTTP 1.0)
• GET and HEAD requests only
• Consider adding caching headers to 3xx and 4xx errors!
• Client-side mechanism usually handled by user agent
Conditional Requests
• Servers
• Last-Modified
• Etag
• Clients
• Validating cached representations
• If-Modified-Since
• If-None-Match
• Preconditions for concurrency control
• If-Unmodified-Since
• If-Match
• One-Time URIs for POSTs
Transactions
• If REST is stateless, how do I support transactions?
• Provide a resource that can make atomic changes to data
• Treat uncommitted state as application state
• If supporting “undos”, use PUT, DELETE, POST as needed
• Asynchronous tasks if long-running
Extensibility & Versioning
• Adding attributes usually not a problem
• JSON (de)serialization basically uses a hashtable
• Clients will lookup values that they expect
• Deleting attributes is the problem
• changing JSON structure is a variant of this
• Array*“missing-key”+ = nada
• format(nada) = *crash*
• Options
• Media type (bad)
• URL (mixed review -> “URIs should remain permanent!”
• Query parameters (OK)
• Domain name (may be OK)
Documenting & Discovery
• Generic Document Template
• All Resources
• All allowed methods for each resource
• Supported media types
• Query Parameters
• URI templates and token definitions
• Role(s) required, if secured
• Link relations, if any
• Discovery
• OPTIONS method
• Supported by Jersey
Security
If service trusts client
Basic Auth
Digest Auth
Otherwise
OAuth
References
Roy Thomas Fielding, Architectural Styles and the Design of Network-based Software Architectures,
http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
RESTful Web Services Cookbook, Subbu Allamaraju
Haters gonna HATEOAS, http://timelessrepo.com/haters-gonna-hateoas
http://www.slideshare.net/joshlong/rest-apis-with-spring
http://bestoked.blogspot.com/2012/02/restful-resources-required-reading.html
http://barelyenough.org/blog/2008/05/versioning-rest-web-services/
http://jacobian.org/writing/rest-worst-practices/
http://restcookbook.com/Miscellaneous/richardsonmaturitymodel/
http://martinfowler.com/articles/richardsonMaturityModel.html
http://www.informit.com/articles/article.aspx?p=1566460
http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http
http://stackoverflow.com/questions/389169/best-practices-for-api-versioning
https://blog.apigee.com/detail/restful_api_design_how_many_versions
Q&A

More Related Content

What's hot

REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API RecommendationsJeelani Shaik
 
Excellent rest using asp.net web api
Excellent rest using asp.net web apiExcellent rest using asp.net web api
Excellent rest using asp.net web api
Maurice De Beijer [MVP]
 
REST & RESTful Web Service
REST & RESTful Web ServiceREST & RESTful Web Service
REST & RESTful Web Service
Hoan Vu Tran
 
Restful webservice
Restful webserviceRestful webservice
Restful webservice
Dong Ngoc
 
Introduction to RESTful Webservices in JAVA
Introduction to RESTful Webservices  in JAVA Introduction to RESTful Webservices  in JAVA
Introduction to RESTful Webservices in JAVA
psrpatnaik
 
Melbourne User Group OAK and MongoDB
Melbourne User Group OAK and MongoDBMelbourne User Group OAK and MongoDB
Melbourne User Group OAK and MongoDB
Yuval Ararat
 
Group meeting: Polaris - Faster Page Loads Using Fine-grained Dependency Trac...
Group meeting: Polaris - Faster Page Loads Using Fine-grained Dependency Trac...Group meeting: Polaris - Faster Page Loads Using Fine-grained Dependency Trac...
Group meeting: Polaris - Faster Page Loads Using Fine-grained Dependency Trac...
Yu-Hsin Hung
 
Orm and hibernate
Orm and hibernateOrm and hibernate
Orm and hibernate
s4al_com
 
HATEOAS: The Confusing Bit from REST
HATEOAS: The Confusing Bit from RESTHATEOAS: The Confusing Bit from REST
HATEOAS: The Confusing Bit from RESTelliando dias
 
Apache Any23 - Anything to Triples
Apache Any23 - Anything to TriplesApache Any23 - Anything to Triples
Apache Any23 - Anything to Triples
Michele Mostarda
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
Kerry Buckley
 
Web services - A Practical Approach
Web services - A Practical ApproachWeb services - A Practical Approach
Web services - A Practical Approach
Madhaiyan Muthu
 
Alfresco Tech Talk Live (Episode 70): Customizing Alfresco Share 4.2
Alfresco Tech Talk Live (Episode 70): Customizing Alfresco Share 4.2Alfresco Tech Talk Live (Episode 70): Customizing Alfresco Share 4.2
Alfresco Tech Talk Live (Episode 70): Customizing Alfresco Share 4.2
Richard Esplin
 
L18 REST API Design
L18 REST API DesignL18 REST API Design
L18 REST API Design
Ólafur Andri Ragnarsson
 
Designing a RESTful web service
Designing a RESTful web serviceDesigning a RESTful web service
Designing a RESTful web serviceFilip Blondeel
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
Sam Brannen
 
ReST
ReSTReST
Resource-Oriented Architecture (ROA) and REST
Resource-Oriented Architecture (ROA) and RESTResource-Oriented Architecture (ROA) and REST
Resource-Oriented Architecture (ROA) and REST
IASA
 
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
J V
 

What's hot (20)

REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
 
Excellent rest using asp.net web api
Excellent rest using asp.net web apiExcellent rest using asp.net web api
Excellent rest using asp.net web api
 
REST & RESTful Web Service
REST & RESTful Web ServiceREST & RESTful Web Service
REST & RESTful Web Service
 
Restful webservice
Restful webserviceRestful webservice
Restful webservice
 
Ntg web services
Ntg   web servicesNtg   web services
Ntg web services
 
Introduction to RESTful Webservices in JAVA
Introduction to RESTful Webservices  in JAVA Introduction to RESTful Webservices  in JAVA
Introduction to RESTful Webservices in JAVA
 
Melbourne User Group OAK and MongoDB
Melbourne User Group OAK and MongoDBMelbourne User Group OAK and MongoDB
Melbourne User Group OAK and MongoDB
 
Group meeting: Polaris - Faster Page Loads Using Fine-grained Dependency Trac...
Group meeting: Polaris - Faster Page Loads Using Fine-grained Dependency Trac...Group meeting: Polaris - Faster Page Loads Using Fine-grained Dependency Trac...
Group meeting: Polaris - Faster Page Loads Using Fine-grained Dependency Trac...
 
Orm and hibernate
Orm and hibernateOrm and hibernate
Orm and hibernate
 
HATEOAS: The Confusing Bit from REST
HATEOAS: The Confusing Bit from RESTHATEOAS: The Confusing Bit from REST
HATEOAS: The Confusing Bit from REST
 
Apache Any23 - Anything to Triples
Apache Any23 - Anything to TriplesApache Any23 - Anything to Triples
Apache Any23 - Anything to Triples
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
 
Web services - A Practical Approach
Web services - A Practical ApproachWeb services - A Practical Approach
Web services - A Practical Approach
 
Alfresco Tech Talk Live (Episode 70): Customizing Alfresco Share 4.2
Alfresco Tech Talk Live (Episode 70): Customizing Alfresco Share 4.2Alfresco Tech Talk Live (Episode 70): Customizing Alfresco Share 4.2
Alfresco Tech Talk Live (Episode 70): Customizing Alfresco Share 4.2
 
L18 REST API Design
L18 REST API DesignL18 REST API Design
L18 REST API Design
 
Designing a RESTful web service
Designing a RESTful web serviceDesigning a RESTful web service
Designing a RESTful web service
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
ReST
ReSTReST
ReST
 
Resource-Oriented Architecture (ROA) and REST
Resource-Oriented Architecture (ROA) and RESTResource-Oriented Architecture (ROA) and REST
Resource-Oriented Architecture (ROA) and REST
 
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
 

Viewers also liked

REpresentational State Transfer
REpresentational State TransferREpresentational State Transfer
REpresentational State TransferVladimir Tsukur
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
Prateek Tandon
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
Nitin Pande
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
Halil Burak Cetinkaya
 
JSON and REST
JSON and RESTJSON and REST
JSON and REST
Robert MacLean
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
Christopher Bartling
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
Stormpath
 
RESTful API 제대로 만들기
RESTful API 제대로 만들기RESTful API 제대로 만들기
RESTful API 제대로 만들기
Juwon Kim
 

Viewers also liked (9)

REpresentational State Transfer
REpresentational State TransferREpresentational State Transfer
REpresentational State Transfer
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
JSON and REST
JSON and RESTJSON and REST
JSON and REST
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
 
RESTful API 제대로 만들기
RESTful API 제대로 만들기RESTful API 제대로 만들기
RESTful API 제대로 만들기
 
RESTful API Design, Second Edition
RESTful API Design, Second EditionRESTful API Design, Second Edition
RESTful API Design, Second Edition
 

Similar to REST Methodologies

RESTful web
RESTful webRESTful web
RESTful web
Alvin Qi
 
Restful风格ž„web服务架构
Restful风格ž„web服务架构Restful风格ž„web服务架构
Restful风格ž„web服务架构
Benjamin Tan
 
CNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application TechnologiesCNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application Technologies
Sam Bowne
 
Boost the Performance of SharePoint Today!
Boost the Performance of SharePoint Today!Boost the Performance of SharePoint Today!
Boost the Performance of SharePoint Today!
Brian Culver
 
Optimization of modern web applications
Optimization of modern web applicationsOptimization of modern web applications
Optimization of modern web applications
Eugene Lazutkin
 
REST Api Tips and Tricks
REST Api Tips and TricksREST Api Tips and Tricks
REST Api Tips and Tricks
Maksym Bruner
 
CNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesCNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application Technologies
Sam Bowne
 
Api Design
Api DesignApi Design
Api Design
Jason Harmon
 
Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Wen-Tien Chang
 
Ch 3: Web Application Technologies
Ch 3: Web Application TechnologiesCh 3: Web Application Technologies
Ch 3: Web Application Technologies
Sam Bowne
 
Rest APIs Training
Rest APIs TrainingRest APIs Training
Rest APIs Training
Shekhar Kumar
 
WebDev Crash Course
WebDev Crash CourseWebDev Crash Course
WebDev Crash Course
Cesar Martinez
 
Building & Testing Scalable Rails Applications
Building & Testing Scalable Rails ApplicationsBuilding & Testing Scalable Rails Applications
Building & Testing Scalable Rails Applicationsevilmike
 
SharePoint Saturday San Antonio: SharePoint 2010 Performance
SharePoint Saturday San Antonio: SharePoint 2010 PerformanceSharePoint Saturday San Antonio: SharePoint 2010 Performance
SharePoint Saturday San Antonio: SharePoint 2010 Performance
Brian Culver
 
Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsReal world RESTful service development problems and solutions
Real world RESTful service development problems and solutions
Masoud Kalali
 
www | HTTP | HTML - Tutorial
www | HTTP | HTML - Tutorialwww | HTTP | HTML - Tutorial
www | HTTP | HTML - Tutorial
MSA Technosoft
 
SharePoint Saturday The Conference 2011 - SP2010 Performance
SharePoint Saturday The Conference 2011 - SP2010 PerformanceSharePoint Saturday The Conference 2011 - SP2010 Performance
SharePoint Saturday The Conference 2011 - SP2010 Performance
Brian Culver
 
Best Practices in Web Service Design
Best Practices in Web Service DesignBest Practices in Web Service Design
Best Practices in Web Service DesignLorna Mitchell
 
Overview of java web services
Overview of java web servicesOverview of java web services
JavaScript Service Worker Design Patterns for Better User Experience
JavaScript Service Worker Design Patterns for Better User ExperienceJavaScript Service Worker Design Patterns for Better User Experience
JavaScript Service Worker Design Patterns for Better User Experience
reeder29
 

Similar to REST Methodologies (20)

RESTful web
RESTful webRESTful web
RESTful web
 
Restful风格ž„web服务架构
Restful风格ž„web服务架构Restful风格ž„web服务架构
Restful风格ž„web服务架构
 
CNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application TechnologiesCNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application Technologies
 
Boost the Performance of SharePoint Today!
Boost the Performance of SharePoint Today!Boost the Performance of SharePoint Today!
Boost the Performance of SharePoint Today!
 
Optimization of modern web applications
Optimization of modern web applicationsOptimization of modern web applications
Optimization of modern web applications
 
REST Api Tips and Tricks
REST Api Tips and TricksREST Api Tips and Tricks
REST Api Tips and Tricks
 
CNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesCNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application Technologies
 
Api Design
Api DesignApi Design
Api Design
 
Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3
 
Ch 3: Web Application Technologies
Ch 3: Web Application TechnologiesCh 3: Web Application Technologies
Ch 3: Web Application Technologies
 
Rest APIs Training
Rest APIs TrainingRest APIs Training
Rest APIs Training
 
WebDev Crash Course
WebDev Crash CourseWebDev Crash Course
WebDev Crash Course
 
Building & Testing Scalable Rails Applications
Building & Testing Scalable Rails ApplicationsBuilding & Testing Scalable Rails Applications
Building & Testing Scalable Rails Applications
 
SharePoint Saturday San Antonio: SharePoint 2010 Performance
SharePoint Saturday San Antonio: SharePoint 2010 PerformanceSharePoint Saturday San Antonio: SharePoint 2010 Performance
SharePoint Saturday San Antonio: SharePoint 2010 Performance
 
Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsReal world RESTful service development problems and solutions
Real world RESTful service development problems and solutions
 
www | HTTP | HTML - Tutorial
www | HTTP | HTML - Tutorialwww | HTTP | HTML - Tutorial
www | HTTP | HTML - Tutorial
 
SharePoint Saturday The Conference 2011 - SP2010 Performance
SharePoint Saturday The Conference 2011 - SP2010 PerformanceSharePoint Saturday The Conference 2011 - SP2010 Performance
SharePoint Saturday The Conference 2011 - SP2010 Performance
 
Best Practices in Web Service Design
Best Practices in Web Service DesignBest Practices in Web Service Design
Best Practices in Web Service Design
 
Overview of java web services
Overview of java web servicesOverview of java web services
Overview of java web services
 
JavaScript Service Worker Design Patterns for Better User Experience
JavaScript Service Worker Design Patterns for Better User ExperienceJavaScript Service Worker Design Patterns for Better User Experience
JavaScript Service Worker Design Patterns for Better User Experience
 

Recently uploaded

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

REST Methodologies

  • 2. Topics • High level on REST • Richardson Maturity Model •Bulk of today’s session • Etc •Data Formats, Caching, Versioning, Discovery, Security • Q&A
  • 3. What is REST? • REST is an architectural constraint based on HTTP 1.1, and created as part of Roy Fielding’s doctoral dissertation in 2000 • It embraces HTTP • It’s not a style, not a standard http://en.wikipedia.org/wiki/Representational_state_transfer http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
  • 4. Richardson Maturity Model …since few REST implementators read Fielding’s thesis • a way to grade your API according to the REST constraints. • the better your API adheres these constraints, the higher its score is. • 4 levels of increasing compliance • Level 3 designates a “truly” RESTful API
  • 5.
  • 6. Level 0: Swamp of POX • POX = Plain Old XML • uses a transport protocol merely for tunneling. No properties of the transfer protocol is used, and all work is done through this tunnel. • Typically uses only one entry point (URI) and one kind of method (in HTTP, this normally is the POST method). • Examples: SOAP and XML-RPC
  • 7. Level 1: Resources • When your API can distinguish between different resources, it might be level 1. • Uses multiple URIs, where every URI is the entry point to a specific resource. • Examples: • /article/1 vs /article/2 • /articles • Still, this level uses only one single method like POST • /articles/create_new
  • 8. URI Design • Slashes – hierarchical • /user/JROD/friends (“ah, this returns a list of JROD’s friends”) • Hyphens or underscores – readability (preferred: hyphens) • /notAGoodWay • /a_better_way • /the-preferred-way • Query String – Filtering: ?, &, = • Semicolons: Matrix parameters, hierarchial, categorical  /reports/some-report/date/2009-03/sort-by/email • Returns email? date? report?  /reports/some-report?date=2009-03&sort-by=email
  • 9. Collection Resources • “Plurals” • /users • /users/JROD/friends • Used for • Paginated views • Filtered views • Create new member resources • Friend request => POST /users/JROD/friends • Perform same operation on multiple resources
  • 10. Composite Resources • Combines information from other resources • Approach #1 • => GET /customer/1234 • => GET /customer/1234/orders?sort_by=date&limit=10 • => GET /customer/1234/quotes?sort_by=date&limit=10&status=pending • Great for modular design, bad for network (chatty) • Can we minimize network overhead without compromising REST? • Approach #2 • => GET /customer/1234/snapshot • <= <snapshot><customer>..</customer><orders>..</orders><quotes>..</quotes></snaps hot>
  • 11. Modifying Multiple Resources • Want to tackle write operations that involve modifying more than one resource atomically? • RESTful controllers • If creating a single resource <= 201 Created, Location • If modifying 1+ resources <= 303 See Other, Location • If more than one Location <= 200 OK, Body: all Locations • Errors
  • 12. Level 2: HTTP Verbs • indicates that your API should use the transport protocol properties in order to deal with scalability and failures • Don't use a single POST method for all, but make use of GET when you are requesting resources, and use the DELETE method when you want to delete a resources • Use HTTP response codes properly • Don't return 200 (OK) when something went wrong. • Use HTTP headers properly
  • 13. HTTP Verbs • GET /user/21  retrieves a resource from a URI • DELETE /user/21  removes the resource • POST /users  creates a new record; returns Location • PUT /user/21  updates a resource
  • 14. PUT vs POST • Some literature seemingly use POST or PUT interchangeably • When do you use PUT vs POST? • POST • URL is decided by server • Response: 201 Created & Location header • If full representation in response, add Content-Location header • PUT • URL decided by client • Response: 201 Created • Preference: PUT for updates, POST for creates
  • 15. Asynchronous Tasks • Some requests take time to complete • Creates (POST), deletes (DELETE) • Multithreaded AJAX controllers can hang! • How to handle? • => POST /imgs/tasks • <= 202 (Accepted), Content-Location: /imgs/task/1, Body: “got it!” • => GET /imgs/task/1 • (still processing) <= 200 (OK), Body: “still processing!” • (done) <= 303 (See Other), Location: /imgs/1, Body: “done!” • (failed) <= 200 (OK), Body: “error reason” • Why 200 on fail? Because task succeeded, image did not
  • 16. Status Codes Convey the result of the server’s attempt to satisfy the request • 1xx: informational • 2xx: success • 3xx: redirection • 4xx: client error • 5xx: server error
  • 17. Error Codes • Client errors • 400 (Bad Request) – missing required HTTP packet info • 401 (Unauthorized) – can be fixed if authenticated • 403 (Forbidden) – don’t try again, can’t access • 404 (Not Found) – never existed or deleted • 405 (Not Allowed) – HTTP method not allowed • 406 (Not Acceptable) – Requested media type not an option • 409 (Conflict) – “request conflicts with current state of resource” • 412 (Precondition Failed) – See conditional requests • 413 (Request Entity Too Large) – POST or PUT request too big, provide limit details • 415 (Unsupported Media Type) – Sent media type not supported
  • 18. Error Codes • Server errors • 500 (Internal Server Error) • Generic; “uhoh, I missed something” = bug • 503 (Service Unavailable) • Database connection • Rate limit • Best practice: include Retry-After header • All errors • Include message in Body (unless method = HEAD)
  • 19. Headers • Content-Type • Prefer to use well-known media types for representations • application/json is the de facto standard for JSON responses • Content-Type = MIME-Type = File format ≠ Schema • Application-specific media types • promote visibility provided that such media types are widely supported • In general, should be avoided as they may reduce interoperability with clients and other tools, such as debuggers and test clients • Last-Modified
  • 20. Level 3: Hypermedia Controls The level where most fall down. There are two parts to this: Content negotiation • focused on different representations of a particular resource HATEAOS • = Hypermedia as the Engine of Application State • No a priori knowledge of service required • Discoverability of actions on a resource. • Navigation options are provided by service and hypermedia controls • Promotes longevity through a uniform interface
  • 21. HATEAOS Links • Provide navigation from a given resource • Dynamic, based on resource state <link href=“/user/232/customers” rel=“customers” />
  • 22. Linking { “links”: * { “rel”: “self” “href”: “…” }, { “rel”: “alternate” “href”: “…” } { “rel”: “previous” “href”: “…” } }
  • 23. Pagination • What to include in collection resources • Links to self, next (if not at end), previous (if not at start) • Size of collection • Example • => GET /articles?contains=cycling&start=10 • <= Body: • total: 1921 • self: “http://foo.com/articles?contains=cycling&start=10” • prev: “http://foo.com/articles?contains=cycling” • next: “http://foo.com/articles?contains=cycling&start=20” • articles: { }
  • 24. Homogeneity • Analogous to supertypes in Java collections • aka don’t rely on Object  • products: [ car: {id, mpg}, boat: {id, hull}]  • products: [ product: ,id, type: “car”, make, model- boat: ,id, type: “boat”, make, model- ]
  • 25. Data Formats • Dates, times, numbers, currencies, etc. • Choosing portable formats for human readability and avoid interoperability errors • Countries & states: ISO-3166: (US, CA) vs. (US-NY, CA-BC) • Currencies: ISO 4217: USD, CAD, JPY • Locales: RFCs 5645, 5646: en-US, en-CA, ja-JP • Dates & times: ISO 8601/RFC 3339 • String sortable/comparable • Human readable (else use Unix epoch) • UTC format prevents time zone issues • E.g., 2013-06-19T11:26:00Z-5:00
  • 26. Caching • Expiration caching in HTTP done in two ways • Expires (HTTP 1.0) • Cache-Control (HTTP 1.1) • Private, public, no-store, etc. • Pragma: no-cache (HTTP 1.0) • GET and HEAD requests only • Consider adding caching headers to 3xx and 4xx errors! • Client-side mechanism usually handled by user agent
  • 27. Conditional Requests • Servers • Last-Modified • Etag • Clients • Validating cached representations • If-Modified-Since • If-None-Match • Preconditions for concurrency control • If-Unmodified-Since • If-Match • One-Time URIs for POSTs
  • 28.
  • 29. Transactions • If REST is stateless, how do I support transactions? • Provide a resource that can make atomic changes to data • Treat uncommitted state as application state • If supporting “undos”, use PUT, DELETE, POST as needed • Asynchronous tasks if long-running
  • 30. Extensibility & Versioning • Adding attributes usually not a problem • JSON (de)serialization basically uses a hashtable • Clients will lookup values that they expect • Deleting attributes is the problem • changing JSON structure is a variant of this • Array*“missing-key”+ = nada • format(nada) = *crash* • Options • Media type (bad) • URL (mixed review -> “URIs should remain permanent!” • Query parameters (OK) • Domain name (may be OK)
  • 31. Documenting & Discovery • Generic Document Template • All Resources • All allowed methods for each resource • Supported media types • Query Parameters • URI templates and token definitions • Role(s) required, if secured • Link relations, if any • Discovery • OPTIONS method • Supported by Jersey
  • 32. Security If service trusts client Basic Auth Digest Auth Otherwise OAuth
  • 33. References Roy Thomas Fielding, Architectural Styles and the Design of Network-based Software Architectures, http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm RESTful Web Services Cookbook, Subbu Allamaraju Haters gonna HATEOAS, http://timelessrepo.com/haters-gonna-hateoas http://www.slideshare.net/joshlong/rest-apis-with-spring http://bestoked.blogspot.com/2012/02/restful-resources-required-reading.html http://barelyenough.org/blog/2008/05/versioning-rest-web-services/ http://jacobian.org/writing/rest-worst-practices/ http://restcookbook.com/Miscellaneous/richardsonmaturitymodel/ http://martinfowler.com/articles/richardsonMaturityModel.html http://www.informit.com/articles/article.aspx?p=1566460 http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http http://stackoverflow.com/questions/389169/best-practices-for-api-versioning https://blog.apigee.com/detail/restful_api_design_how_many_versions
  • 34. Q&A