SlideShare a Scribd company logo
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

An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Aniruddh Bhilvare
 
Postman Collection Format v2.0 (pre-draft)
Postman Collection Format v2.0 (pre-draft)Postman Collection Format v2.0 (pre-draft)
Postman Collection Format v2.0 (pre-draft)
Postman
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
Suraj Gupta
 
Pentesting ReST API
Pentesting ReST APIPentesting ReST API
Pentesting ReST API
Nutan Kumar Panda
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
Cakra Danu Sedayu
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2
Sanjoy Kumar Roy
 
An Introduction to OAuth 2
An Introduction to OAuth 2An Introduction to OAuth 2
An Introduction to OAuth 2
Aaron Parecki
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
Apaichon Punopas
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 
Lezione 8: Introduzione ai Web Service
Lezione 8: Introduzione ai Web ServiceLezione 8: Introduzione ai Web Service
Lezione 8: Introduzione ai Web Service
Andrea Della Corte
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
Prem Sanil
 
Rest API
Rest APIRest API
API Testing Using REST Assured with TestNG
API Testing Using REST Assured with TestNGAPI Testing Using REST Assured with TestNG
API Testing Using REST Assured with TestNG
Siddharth Sharma
 
OAuth 2.0 and OpenId Connect
OAuth 2.0 and OpenId ConnectOAuth 2.0 and OpenId Connect
OAuth 2.0 and OpenId Connect
Saran Doraiswamy
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
Yao Nien Chung
 
Getting Started with API Security Testing
Getting Started with API Security TestingGetting Started with API Security Testing
Getting Started with API Security Testing
SmartBear
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
Patrick Savalle
 
REST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTsREST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTs
Jon Todd
 
Rest assured
Rest assuredRest assured
Rest assured
Varun Deshpande
 

What's hot (20)

An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Postman Collection Format v2.0 (pre-draft)
Postman Collection Format v2.0 (pre-draft)Postman Collection Format v2.0 (pre-draft)
Postman Collection Format v2.0 (pre-draft)
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
 
Pentesting ReST API
Pentesting ReST APIPentesting ReST API
Pentesting ReST API
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2
 
Soap vs rest
Soap vs restSoap vs rest
Soap vs rest
 
An Introduction to OAuth 2
An Introduction to OAuth 2An Introduction to OAuth 2
An Introduction to OAuth 2
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Lezione 8: Introduzione ai Web Service
Lezione 8: Introduzione ai Web ServiceLezione 8: Introduzione ai Web Service
Lezione 8: Introduzione ai Web Service
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
Rest API
Rest APIRest API
Rest API
 
API Testing Using REST Assured with TestNG
API Testing Using REST Assured with TestNGAPI Testing Using REST Assured with TestNG
API Testing Using REST Assured with TestNG
 
OAuth 2.0 and OpenId Connect
OAuth 2.0 and OpenId ConnectOAuth 2.0 and OpenId Connect
OAuth 2.0 and OpenId Connect
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
Getting Started with API Security Testing
Getting Started with API Security TestingGetting Started with API Security Testing
Getting Started with API Security Testing
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
 
REST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTsREST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTs
 
Rest assured
Rest assuredRest assured
Rest assured
 

Similar to Spring HATEOAS

RESTFul WebApp Concept
RESTFul WebApp ConceptRESTFul WebApp Concept
RESTFul WebApp ConceptDian Aditya
 
RESTFul WebApp Concept
RESTFul WebApp ConceptRESTFul WebApp Concept
RESTFul WebApp ConceptDian Aditya
 
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
Jonathan LeBlanc
 
Have You Seen Spring Lately?
Have You Seen Spring Lately?Have You Seen Spring Lately?
Have You Seen Spring Lately?
Joshua Long
 
Дмитрий Красун: Сегодня вы уйдете с новым представлением о REST
Дмитрий Красун: Сегодня вы уйдете с новым представлением о RESTДмитрий Красун: Сегодня вы уйдете с новым представлением о REST
Дмитрий Красун: Сегодня вы уйдете с новым представлением о REST
Oleg Poludnenko
 
WebApp #3 : API
WebApp #3 : APIWebApp #3 : API
WebApp #3 : API
Jean Michel
 
Standards of rest api
Standards of rest apiStandards of rest api
Standards of rest api
Maýur Chourasiya
 
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
Philip Johnson
 
Creating Restful Web Services with restish
Creating Restful Web Services with restishCreating Restful Web Services with restish
Creating Restful Web Services with restish
Grig Gheorghiu
 
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
Jenkins NS
 
Modified REST Presentation
Modified REST PresentationModified REST Presentation
Modified REST Presentation
Alexandros Marinos
 
Hypermedia APIs and HATEOAS / Wix Engineering
Hypermedia APIs and HATEOAS / Wix EngineeringHypermedia APIs and HATEOAS / Wix Engineering
Hypermedia APIs and HATEOAS / Wix Engineering
Vladimir Tsukur
 
Salesforce REST API
Salesforce  REST API Salesforce  REST API
Salesforce REST API
Bohdan Dovhań
 
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.
Mario Cardinal
 
RESTing with JAX-RS
RESTing with JAX-RSRESTing with JAX-RS
RESTing with JAX-RS
Ezewuzie Emmanuel Okafor
 
Introduction To REST
Introduction To RESTIntroduction To REST
Introduction To REST
rainynovember12
 
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
Jerry Kurian
 
Together Cheerfully to Walk with Hypermedia
Together Cheerfully to Walk with HypermediaTogether Cheerfully to Walk with Hypermedia
Together Cheerfully to Walk with Hypermedia
Vladimir Tsukur
 

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

RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 

Recently uploaded (20)

RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 

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: