SlideShare a Scribd company logo
1 of 25
Spring HATEOAS
By Yoann Buch & Yiquan Zhou
Spring meetup 24/02/2016
Qui sommes nous ?
➔ 2 développeurs
➔ Lancent une entreprise autour d’un outil de développement
http://findtheflow.io
➔ Focalisent sur la visualisation et analyse des exécutions de programmes
➔ Utilisent de nombreux projets de Spring : Boot, MVC, HATEOAS,
Websocket, Integration, Batch, etc.
Concept
Humains et
hypermedia
Machines et
hypermedia
Définition
Modèle de maturité REST
source: http://martinfowler.com/articles/richardsonMaturityModel.html
Utiliser HTTP
Modélisation en
resources
CRUD opération
HATEOAS
Notre exemple d’application
Construire une API
Consulter le menu
Commander des boissons
Payer la commande
Vérifier le statut de préparation de commande
...
R E S T B U C K S
Source: “REST in Practice: Hypermedia and Systems Architecture”
Level 0: POX
Une URI, une methode
SOAP, XML RPC, POX
Request Response
POST /coffeeService HTTP/1.1
Content-Type: application/xml
<request xmlns=”http://restbucks.com”>
<placeOrder>
<customer>Mike</customer>
<location>takeAway</location>
<items>...</items>
</placeOrder>
…
</request>
HTTP/1.1 200 OK
Content-Type: application/xml
<response xmlns=”http://restbucks.com”>
<success>true</success>
<orderConfirmation>
<orderId>1234</orderId>
</orderConfirmation>
<error/>
</response>
Level 1: Resources
URI unique pour chaque ressource
Un seul verbe HTTP sans sémantique
Request Response
POST /orders HTTP/1.1
Content-Type: application/xml
<orderRequest>
<operation>create</operation>
<customer>Mike</customer>
<location>takeAway</location>
<items>...</items>
…
</orderRequest>
HTTP/1.1 200 OK
Content-Type: application/xml
<orderResponse>
<success>true</success>
<orderId>1234</orderId>
<error/>
</orderResponse>
Level 2: HTTP verbs
Multiples URIs, multiples verbes
Status code
Request Response
POST /orders HTTP/1.1
Content-Type: application/xml
<order>
<customer>Mike</customer>
<location>takeAway</location>
<items>...</items>
…
</order>
GET /orders/1234
PUT /orders/1234
DELETE /orders/1234
HTTP/1.1 201 CREATED
Content-Type: application/xml
Location: http://restbucks.com/orders/1234
<order>
<customer>Mike</customer>
<location>takeAway</location>
<items>...</items>
<status>payment-expected</status>
</order>
Hypermedia As The Engine Of Application State
Level 3 : HATEOAS
protocole Objectif
état
Transfert des liens
dans des ressources
Level 3: HATEOAS
Submitted Paid
Canceled
Preparing Completed
place
update
cancel
pay
check status
deliver
planned
Transition d’états d’une commande
HATEOAS => Définir les transitions d’états dans la représentation des ressources
Level 3: HATEOAS
Request Response
POST /orders HTTP/1.1
Content-Type: application/xml
<order>
<customer>Mike</customer>
<location>takeAway</location>
<items>...</items>
…
</order>
HTTP/1.1 201 CREATED
Content-Type: application/vnd.restbucks+xml
Location: http://restbucks.com/orders/1234
<order>
<customer>Mike</customer>
<location>takeAway</location>
<items>...</items>
<status>payment-expected</status>
<restbucks:link rel=”pay”
href=”https://restbucks.com/orders/1234/payment”/>
<restbucks:link rel=”update”
href=”https://restbucks.com/orders/1234”/>
<restbucks:link rel=”cancel”
href=”https://restbucks.com/orders/1234”/>
</order>
Formats hypermedia
Contrat pour trouver et interpréter les liens.
Formats standards:
application/xhtml+xml
application/atom+xml
application/hal+json / application/hal+xml
…
<person xmlns:atom="http://www.w3.org/2005/Atom">
<firstname>Dave</firstname>
<lastname>Matthews</lastname>
<links>
<atom:link rel="self" href="http://myhost/people/1" />
</links>
</person>
Formats specifiques:
application/vnd.mycompany.myapp+xml
application/vnd.mycompany.myapp+json
...
Implémentation
Hypermedia et Spring : Spring HATEOAS
Introduit concepts de ressources et liens
Resource(s), ResourceSupport, Link
Facilite la génération d’URIs
linkTo et methodOn
Serialize au format HAL (XML et JSON)
Facilite la consommation des liens
HalkLinkDiscoverer, Traverson
Facilite l’assemblage des ressources
ResourceAssembler
Liens
Link link = new Link("http://localhost:8080/something");
assertThat(link.getHref(), is("http://localhost:8080/something"));
assertThat(link.getRel(), is(Link.SELF));
Link link = new Link("http://localhost:8080/something", "my-rel");
assertThat(link.getHref(), is("http://localhost:8080/something"));
assertThat(link.getRel(), is("my-rel"));
Source : http://docs.spring.io/spring-hateoas/docs/0.19.0.RELEASE/reference/html
Ressources
class PersonResource extends ResourceSupport {
String firstname;
String lastname;
}
PersonResource resource = new PersonResource();
resource.firstname = "Dave";
resource.lastname = "Matthews";
resource.add(new Link("http://myhost/people"));
{
firstname : "Dave",
lastname : "Matthews",
links : [ {
rel : "self",
href : "http://myhost/people"
} ]
}
Générer des URIs
Link link = linkTo(methodOn(PersonController.class).show(2L)).withSelfRel();
assertThat(link.getHref(), is("http://localhost:8080//people/2")));
Découvrir et récuperer des liens
String content = "{'_links' : { 'foo' : { 'href' : '/foo/bar' }}}";
LinkDiscoverer discoverer = new HalLinkDiscoverer();
Link link = discoverer.findLinkWithRel("foo", content);
assertThat(link.getHref(), is("/foo/bar"));
Consommer une API hypermedia - Java
Consommer une API hypermedia - JavaScript
// traverson
traverson.json.from("http://api.github.com")
.newRequest()
.follow('repository_url', 'branches_url')
.withTemplateParameters({
owner: 'spring-projects',
repo: 'spring-hateoas',
branch: 'master'
}).getResource(function(err, resource) {
if (err) { console.log(err); return; }
console.log(resource);
// do something else
})
})
// jquery ajax
$.get("http://api.github.com", function(resource) {
var uri = nextUri(resource, 'repository_url')
uri = uri.replace(/{owner}/, 'spring-projects')
uri = uri.replace(/{repo}/, 'spring-hateoas')
$.get(uri, function(resource) {
uri = nextUri(resource, 'branches_url')
uri = uri.replace(/{/branch}/, '/master')
$.get(uri, function(resource) {
console.log(resource);
// do something else
})
})
})
function nextUri(resource, link) {
return resource[link]
}
https://github.com/basti1302/traverson-hal
HATEOAS
API explorable et auto-descriptive
➔Meilleure adoption de l’API
➔Mettre en avant des nouvelles fonctionnalités
Logique client simple
➔Pas d’URIs en dur
➔Client suit un protocole
Couplage faible entre serveur et client
➔Client résistant au changement des URIs
➔Moins de dépendences aux URI templates ou
langages de définition (ex. WSDL, WADL)
Pour aller plus loin
Livre : “REST in Practice: Hypermedia and Systems Architecture”
Spring Restbucks (et notre notre version simplifiee)
Bons examples en production (FoxyCart, PayPal, etc.)
Spring Data REST
HAL Browser
Spring REST Docs
CURIEs
Traitement des erreurs avec vnd.error
Retour d’expérience : http://findtheflow.io

More Related Content

What's hot

What Is Apache Spark? | Introduction To Apache Spark | Apache Spark Tutorial ...
What Is Apache Spark? | Introduction To Apache Spark | Apache Spark Tutorial ...What Is Apache Spark? | Introduction To Apache Spark | Apache Spark Tutorial ...
What Is Apache Spark? | Introduction To Apache Spark | Apache Spark Tutorial ...
Simplilearn
 

What's hot (20)

REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
jQuery
jQueryjQuery
jQuery
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
 
Node js overview
Node js overviewNode js overview
Node js overview
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Apache Hive Tutorial
Apache Hive TutorialApache Hive Tutorial
Apache Hive Tutorial
 
Rest API Security
Rest API SecurityRest API Security
Rest API Security
 
Express node js
Express node jsExpress node js
Express node js
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
jQuery
jQueryjQuery
jQuery
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask Presentation
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSS
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
 
Dhtml ppt (2)
Dhtml ppt (2)Dhtml ppt (2)
Dhtml ppt (2)
 
What Is Apache Spark? | Introduction To Apache Spark | Apache Spark Tutorial ...
What Is Apache Spark? | Introduction To Apache Spark | Apache Spark Tutorial ...What Is Apache Spark? | Introduction To Apache Spark | Apache Spark Tutorial ...
What Is Apache Spark? | Introduction To Apache Spark | Apache Spark Tutorial ...
 

Similar to Spring HATEOAS

RESTFul WebApp Concept
RESTFul WebApp ConceptRESTFul WebApp Concept
RESTFul WebApp Concept
Dian Aditya
 
RESTFul WebApp Concept
RESTFul WebApp ConceptRESTFul WebApp Concept
RESTFul WebApp Concept
Dian Aditya
 

Similar to Spring HATEOAS (20)

Today's Spring framework
Today's Spring frameworkToday's Spring framework
Today's Spring framework
 
RESTFul WebApp Concept
RESTFul WebApp ConceptRESTFul WebApp Concept
RESTFul WebApp Concept
 
RESTFul WebApp Concept
RESTFul WebApp ConceptRESTFul WebApp Concept
RESTFul WebApp Concept
 
Securing RESTful APIs using OAuth 2 and OpenID Connect
Securing RESTful APIs using OAuth 2 and OpenID ConnectSecuring RESTful APIs using OAuth 2 and OpenID Connect
Securing RESTful APIs using OAuth 2 and OpenID Connect
 
Rest and Rails
Rest and RailsRest and Rails
Rest and Rails
 
Have You Seen Spring Lately?
Have You Seen Spring Lately?Have You Seen Spring Lately?
Have You Seen Spring Lately?
 
Дмитрий Красун: Сегодня вы уйдете с новым представлением о REST
Дмитрий Красун: Сегодня вы уйдете с новым представлением о RESTДмитрий Красун: Сегодня вы уйдете с новым представлением о REST
Дмитрий Красун: Сегодня вы уйдете с новым представлением о REST
 
WebApp #3 : API
WebApp #3 : APIWebApp #3 : API
WebApp #3 : API
 
Standards of rest api
Standards of rest apiStandards of rest api
Standards of rest api
 
Introduction to REST and the Restlet Framework
Introduction to REST and the Restlet FrameworkIntroduction to REST and the Restlet Framework
Introduction to REST and the Restlet Framework
 
Creating Restful Web Services with restish
Creating Restful Web Services with restishCreating Restful Web Services with restish
Creating Restful Web Services with restish
 
SPFx Webinar Loading SharePoint data in a SPFx Webpart
SPFx Webinar Loading SharePoint data in a SPFx WebpartSPFx Webinar Loading SharePoint data in a SPFx Webpart
SPFx Webinar Loading SharePoint data in a SPFx Webpart
 
Modified REST Presentation
Modified REST PresentationModified REST Presentation
Modified REST Presentation
 
Hypermedia APIs and HATEOAS / Wix Engineering
Hypermedia APIs and HATEOAS / Wix EngineeringHypermedia APIs and HATEOAS / Wix Engineering
Hypermedia APIs and HATEOAS / Wix Engineering
 
Salesforce REST API
Salesforce  REST API Salesforce  REST API
Salesforce REST API
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 
RESTing with JAX-RS
RESTing with JAX-RSRESTing with JAX-RS
RESTing with JAX-RS
 
Introduction To REST
Introduction To RESTIntroduction To REST
Introduction To REST
 
JAX-RS. Developing RESTful APIs with Java
JAX-RS. Developing RESTful APIs with JavaJAX-RS. Developing RESTful APIs with Java
JAX-RS. Developing RESTful APIs with Java
 
Together Cheerfully to Walk with Hypermedia
Together Cheerfully to Walk with HypermediaTogether Cheerfully to Walk with Hypermedia
Together Cheerfully to Walk with Hypermedia
 

Recently uploaded

Introduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxIntroduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptx
hublikarsn
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
HenryBriggs2
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
Kamal Acharya
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 

Recently uploaded (20)

School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Introduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxIntroduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptx
 
Signal Processing and Linear System Analysis
Signal Processing and Linear System AnalysisSignal Processing and Linear System Analysis
Signal Processing and Linear System Analysis
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using PipesLinux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Worksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptxWorksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptx
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth Reinforcement
 
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptx
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 

Spring HATEOAS

  • 1. Spring HATEOAS By Yoann Buch & Yiquan Zhou Spring meetup 24/02/2016
  • 2. Qui sommes nous ? ➔ 2 développeurs ➔ Lancent une entreprise autour d’un outil de développement http://findtheflow.io ➔ Focalisent sur la visualisation et analyse des exécutions de programmes ➔ Utilisent de nombreux projets de Spring : Boot, MVC, HATEOAS, Websocket, Integration, Batch, etc.
  • 7. Modèle de maturité REST source: http://martinfowler.com/articles/richardsonMaturityModel.html Utiliser HTTP Modélisation en resources CRUD opération HATEOAS
  • 8. Notre exemple d’application Construire une API Consulter le menu Commander des boissons Payer la commande Vérifier le statut de préparation de commande ... R E S T B U C K S Source: “REST in Practice: Hypermedia and Systems Architecture”
  • 9. Level 0: POX Une URI, une methode SOAP, XML RPC, POX Request Response POST /coffeeService HTTP/1.1 Content-Type: application/xml <request xmlns=”http://restbucks.com”> <placeOrder> <customer>Mike</customer> <location>takeAway</location> <items>...</items> </placeOrder> … </request> HTTP/1.1 200 OK Content-Type: application/xml <response xmlns=”http://restbucks.com”> <success>true</success> <orderConfirmation> <orderId>1234</orderId> </orderConfirmation> <error/> </response>
  • 10. Level 1: Resources URI unique pour chaque ressource Un seul verbe HTTP sans sémantique Request Response POST /orders HTTP/1.1 Content-Type: application/xml <orderRequest> <operation>create</operation> <customer>Mike</customer> <location>takeAway</location> <items>...</items> … </orderRequest> HTTP/1.1 200 OK Content-Type: application/xml <orderResponse> <success>true</success> <orderId>1234</orderId> <error/> </orderResponse>
  • 11. Level 2: HTTP verbs Multiples URIs, multiples verbes Status code Request Response POST /orders HTTP/1.1 Content-Type: application/xml <order> <customer>Mike</customer> <location>takeAway</location> <items>...</items> … </order> GET /orders/1234 PUT /orders/1234 DELETE /orders/1234 HTTP/1.1 201 CREATED Content-Type: application/xml Location: http://restbucks.com/orders/1234 <order> <customer>Mike</customer> <location>takeAway</location> <items>...</items> <status>payment-expected</status> </order>
  • 12. Hypermedia As The Engine Of Application State Level 3 : HATEOAS protocole Objectif état Transfert des liens dans des ressources
  • 13. Level 3: HATEOAS Submitted Paid Canceled Preparing Completed place update cancel pay check status deliver planned Transition d’états d’une commande HATEOAS => Définir les transitions d’états dans la représentation des ressources
  • 14. Level 3: HATEOAS Request Response POST /orders HTTP/1.1 Content-Type: application/xml <order> <customer>Mike</customer> <location>takeAway</location> <items>...</items> … </order> HTTP/1.1 201 CREATED Content-Type: application/vnd.restbucks+xml Location: http://restbucks.com/orders/1234 <order> <customer>Mike</customer> <location>takeAway</location> <items>...</items> <status>payment-expected</status> <restbucks:link rel=”pay” href=”https://restbucks.com/orders/1234/payment”/> <restbucks:link rel=”update” href=”https://restbucks.com/orders/1234”/> <restbucks:link rel=”cancel” href=”https://restbucks.com/orders/1234”/> </order>
  • 15. Formats hypermedia Contrat pour trouver et interpréter les liens. Formats standards: application/xhtml+xml application/atom+xml application/hal+json / application/hal+xml … <person xmlns:atom="http://www.w3.org/2005/Atom"> <firstname>Dave</firstname> <lastname>Matthews</lastname> <links> <atom:link rel="self" href="http://myhost/people/1" /> </links> </person> Formats specifiques: application/vnd.mycompany.myapp+xml application/vnd.mycompany.myapp+json ...
  • 17. Hypermedia et Spring : Spring HATEOAS Introduit concepts de ressources et liens Resource(s), ResourceSupport, Link Facilite la génération d’URIs linkTo et methodOn Serialize au format HAL (XML et JSON) Facilite la consommation des liens HalkLinkDiscoverer, Traverson Facilite l’assemblage des ressources ResourceAssembler
  • 18. Liens Link link = new Link("http://localhost:8080/something"); assertThat(link.getHref(), is("http://localhost:8080/something")); assertThat(link.getRel(), is(Link.SELF)); Link link = new Link("http://localhost:8080/something", "my-rel"); assertThat(link.getHref(), is("http://localhost:8080/something")); assertThat(link.getRel(), is("my-rel")); Source : http://docs.spring.io/spring-hateoas/docs/0.19.0.RELEASE/reference/html
  • 19. Ressources class PersonResource extends ResourceSupport { String firstname; String lastname; } PersonResource resource = new PersonResource(); resource.firstname = "Dave"; resource.lastname = "Matthews"; resource.add(new Link("http://myhost/people")); { firstname : "Dave", lastname : "Matthews", links : [ { rel : "self", href : "http://myhost/people" } ] }
  • 20. Générer des URIs Link link = linkTo(methodOn(PersonController.class).show(2L)).withSelfRel(); assertThat(link.getHref(), is("http://localhost:8080//people/2"))); Découvrir et récuperer des liens String content = "{'_links' : { 'foo' : { 'href' : '/foo/bar' }}}"; LinkDiscoverer discoverer = new HalLinkDiscoverer(); Link link = discoverer.findLinkWithRel("foo", content); assertThat(link.getHref(), is("/foo/bar"));
  • 21. Consommer une API hypermedia - Java
  • 22. Consommer une API hypermedia - JavaScript // traverson traverson.json.from("http://api.github.com") .newRequest() .follow('repository_url', 'branches_url') .withTemplateParameters({ owner: 'spring-projects', repo: 'spring-hateoas', branch: 'master' }).getResource(function(err, resource) { if (err) { console.log(err); return; } console.log(resource); // do something else }) }) // jquery ajax $.get("http://api.github.com", function(resource) { var uri = nextUri(resource, 'repository_url') uri = uri.replace(/{owner}/, 'spring-projects') uri = uri.replace(/{repo}/, 'spring-hateoas') $.get(uri, function(resource) { uri = nextUri(resource, 'branches_url') uri = uri.replace(/{/branch}/, '/master') $.get(uri, function(resource) { console.log(resource); // do something else }) }) }) function nextUri(resource, link) { return resource[link] } https://github.com/basti1302/traverson-hal
  • 23. HATEOAS API explorable et auto-descriptive ➔Meilleure adoption de l’API ➔Mettre en avant des nouvelles fonctionnalités Logique client simple ➔Pas d’URIs en dur ➔Client suit un protocole Couplage faible entre serveur et client ➔Client résistant au changement des URIs ➔Moins de dépendences aux URI templates ou langages de définition (ex. WSDL, WADL)
  • 24. Pour aller plus loin Livre : “REST in Practice: Hypermedia and Systems Architecture” Spring Restbucks (et notre notre version simplifiee) Bons examples en production (FoxyCart, PayPal, etc.) Spring Data REST HAL Browser Spring REST Docs CURIEs Traitement des erreurs avec vnd.error
  • 25. Retour d’expérience : http://findtheflow.io

Editor's Notes

  1. ice breakers: rappeler le talk de Spring Cloud? demander a l’audience leur niveau avec REST et HATEOAS ha-TAY-oh-ahss
  2. HTML supports hypermedia (urls and forms) When browsing the Web, we’re used to navigating between pages by clicking links or completing and submitting forms. In a typical e-commerce solution such as amazon.com, the server generates web pages with links on them that corral the user through the process of selecting goods, purchasing, and arranging delivery. consulter les articles -> ajouter au panier -> passer la commande (livraison, paiement, confirmation) un point d’entree, suivre les etapes;
  3. A quoi ça ressemble dans une intéraction entre machines? https://api.github.com https://api.github.com/users/spring-projects https://api.github.com/repos/spring-projects/spring-hateoas
  4. = ou se situe l’hypermedia dans architecture REST (Representational State Transfer) http://martinfowler.com/articles/richardsonMaturityModel.html Level 0: une URI, une methode SOAP, XML RPC, POX blackbox Level 1: Chaque ressource est identifiée par une URI unique une seule verbe HTTP qui n’a pas de sémantique Level 2: Multiples URIs, multiples verbes + status code CRUD Level 3: ressources sont auto-descriptives RESTful
  5. = HATEOAS c’est quoi hypermedia as the engine of application state hypermedia: a hypermedia system is characterized by the transfer of links in the resource representations exchanged by the participants in an application protocol état d’application: objectif applicatif | protocol des interactions | snapshot d’execution du protocol ex. restbucks: commander un café | initier une commande, payer | L’etat / la représentation d’une ressource est composé de: les valeurs de ses attributs les liens vers d’autres ressources les liens representant une transition possible vers un état futur de la ressource actuelle diagramme etat
  6. diagramme complet pour la ressource commande
  7. standard = facile a implementer et consommer format = liens vers ressources + annotations semantiques (comment interpreter la ressource) rel = what is this link? method, doc contextuelle, accepts/produces media types http://ionwg.github.io/draft-ion.html
  8. Demo Level 2: Source code Creation commande PB: faut connaitre le lien Location header Cancel Payment Montrer que c’est pas explorable, pas de protocole Level 3: Browser Montrer ce que l’on veut obtenir Source code Ressource racine Creation ressource Creation liens avec linkTo Creation liens en fonction de l’etat de la ressource REST Client payment scenario Automated testing suivi du protocole trouver liens dans les reponses jsonpath utilisation de RestTemplate (et non Traverson)
  9. Traverson ne supporte que GET => RestTemplate
  10. jquery ajax: recuperer la resource, parser l’uri, remplacer les parametres puis répéter le même process => callback pyramid traverson: suivre une séquence de liens jusqu’à la resource target éviter callback pyramid https://blog.codecentric.de/en/2013/11/traverson/
  11. explorable API / inline documentation permet aux développeurs de découvrir l’API et structure de données facilement, au lieu de switcher constamment entre code et la doc => meilleure adoption de l’API Moins besoin de se referer a la doc simple client logic (no more uri hardcoding) Le client suit les uri au lieu de les construire loose coupling between server and client server can change URIs (including pointing to different domains) advertise new functionalities less dependency on URI templates or WADL/WSDL) URIs sont des implementations, le client n’a pas a les connaitre Les http://soabits.blogspot.no/2013/12/selling-benefits-of-hypermedia.html
  12. TODO: lien vers version simplifiee = findtheflow.io#relatedprojects
  13. retour d’experience + pub business value: enregistre l’exécution donnée stocké et comment on les valorise donnée très hiérarchique et explorable grâce aux HATEOAS questions a repondre: inconvenient? surcout risque de mal faire migration impossible surtout cote client, le principe change impact sur perf? (embedded ressources, caching) quel niveau pour vous ? vous avez ca en prod ? questions a leur poser: