COMPRENDRE L’ARCHITECTURE DES
WEB SERVICES REST
Amosse EDOUARD, Doctorant
Organisation
¨ Cours Magistral
¤ 24/11/2014
¤ 26/11/2014
¤ 01/12/2014
¨ Travaux Dirigés
¤ 26/11/2014
¤ 28/11/2014
¤ 01/11/2014
¤ 08/11/2014
Evaluation
¨ Présence, Participationè 20%
¨ Mini Projet è 40%
¨ Examen Théorique è 40%
Objectifs du cours
¨ SOAP
¤ Initiation au protocole et les Web services SOAP
¤ Comprendre les enveloppes SOAP
¤ Créer et tester des services SOAP
¨ REST
¤ Comprendre l’architecture des applications compatibles
REST
¤ Exposer des services REST
¤ Consommer des services REST dans de applications Web
Rappel à Protocol HTTP
Le Protocole HTTP
¨ HyperText Transfer Protocol
¨ Protocole d’échanges d’information sur le web
¨ Basé sur TCP/IP
Requête HTTP
Réponse HTTP
HTTP Clients HTTP Server
Enchainement Client Serveur
URL
¨ Unique Resource Location
¨ Identifie les ressources de manière unique sur le
Web
¨ 4 parties
¤ Protocole(http, ftp, mail, …)
¤ Host (google.com)
¤ Port (8080, 80)
¤ Path (Chemin vers la ressource sur le serveur)
Requêtes HTTP
¨ Permet à un client d’envoyer des messages à un
serveur
¨ Format d’un message HTTP
¤ Request Message Header
n Request Line
n Request Headers [Optional]
¤ Request Message Body
Request Message Header
¨ Request Line
POST /bibliotheque/faces/views/categorie/Create.xhtml HTTP/1.1
¨ Request Headers
Host: localhost:8080
Connection: keep-alive
Content-Length: 176
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/
39.0.2171.65 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:8080/bibliotheque/faces/views/categorie/List.xhtml
Accept-Encoding: gzip, deflate
Accept-Language: fr,fr-FR;q=0.8,en;q=0.6
Cookie: JSESSIONID=d64a9484e61761662575b5d14af1
Request Message Body
¨ Contient les données supplémentaires envoyées au
serveur
j_idt13:nom:Miage
j_idt13:description:NTDP
Réponse HTTP
¨ Réponse du serveur au client
¨ Format d’une réponse HTTP
¤ Response Message Header
n Response Line
n Response Headers
¤ Response Message [Optional]
Response Message Header
¨ Response Line
HTTP/1.1 200 OK
¨ Response Headers
HTTP/1.1 200 OK
X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.0 Java/Oracle Corporation/1.8)
Server: GlassFish Server Open Source Edition 4.0
Content-Type: text/html;charset=UTF-8
Date: Sun, 23 Nov 2014 16:05:39 GMT
Content-Length: 2274
Response Message Body
¨ Response Body
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><html xmlns="http://www.w3.org/1999/xhtml"><head><link
type="text/css" rel="stylesheet" href="/bibliotheque/faces/javax.faces.resource/theme.css?ln=primefaces-aristo" /
><link type="text/css" rel="stylesheet" href="/bibliotheque/faces/javax.faces.resource/css/jsfcrud.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Create New Categorie</title></head><body>
<h1>Create New Categorie
</h1>
<p><div id="messagePanel"><table><tr style="color: green"><td>Categorie was successfully created. </td>
</tr></table></div>
</html>
</html>
Méthodes HTTP
¨ HTTP définit un ensemble de méthode permet de
caractériser les requêtes
¤ GET : Récupérer des ressources à un serveur
¤ POST : Envoyer des données à un serveur
¤ PUT : Modifier des données
¤ DELETE : Suppression de données
¤ OPTIONS : Demander la liste des méthodes supportées
par un serveur
¤ Autres : HEAD, TRACE, CONNECT
Partie 1
Introduction aux Web Services
Utilisation du web aujourd’hui (1)
1
2 2
1
2
2
1 Serveur d’applications
1
1
2
2
1
2 2
Serveur d’applications
Demande de ressources
Resources
Web Services (Définition)
q Services informatiques de la famille des technologies
web permettant la communication entre des
applications hétérogènes dans des environnements
distribués (Wikipédia).
q Ils ont été proposé à la base comme solution
d’intégrations de différents logiciels développés par
des entreprises (ERP, SCM, CRM) leur permettant de
communiquer entre eux.
q Basés sur XML (déscription et échange) et utilisant en
général les protocoles du web comme canal de
communication;
Types de Services Webs
¨ Deux principaux types
¤ SOAP
¤ REST
Web Services SOAP
¨ Simple Object Access Protocol
¨ Protocole d’échanges d’informations dans un
environnement distribué basé sur XML
¤ Interopérabilité entre applications d’une même
entreprise (Intranet)
¤ Interopérabilité inter entreprises entre applications et
services web
¨ Similaire au protocole RCP,
Web Services SOAP
¨ SOAP peut être utilisé de concert avec plusieurs
autres protocoles : HTTP, SMTP, POP
à HTTP est le plus utilisé
Web Services SOAP
Web Services SOAP
¨ SOAP est principalement composé de trois parties:
¤ Les enveloppes SOAP (ou Message)
¤ Les règles d’encodages
¤ La représentation RPC
Messages SOAP
¨ L’Enveloppe SOAP à Obligatoire
¤ Une en-tête (Header) à Optionnel
¤ Le corps (Body) à Obligatoire
Messages SOAP
¨ Les messages SOAP sont utilisés pour envoyer (requête) et recevoir
(réponse) des informations d’un consommateur vers un producteur
¨ Un message SOAP peut être transmis à plusieurs récepteurs
intermédiaires avant d’être reçu par le récepteur final (è chaîne de
responsabilité)
¨ Le format SOAP peut contenir des messages spécifiques
correspondant à des erreurs identifiées par le récepteur
¨ Un message SOAP est véhiculé en utilisant un protocole de transport
(HTTP, SMTP, …)
SOAP : WSDL
¨ Web Service Description Language
¨ Fichier au format XML
¨ Décrit les actions exposées par le web service
SOAP – Exemples d’utilisation
Annuaire UDDI
Interroger
l’annuaire
pour obtenir
les services Publication
disponibles des services
offerts
(*.wsdl)
2 1
3
Télécharger le Interroger le
document descriptif service
du service choisi conformément
(*.wsdl) au WSDL
5
Entreprise 1
Consommateur de service Répond aux requetes par des Entreprise 2
messages SOAP conforme au Producteur de service
WSDL
SOAP : Enveloppe
¨ Constitue la racine d’un message SOAP
¨ Identifié par la balise <namespace:Envelop>
¨ La balise doit être obligatoirement associé à un
espace de noms [spec W3C]
¨ SOAP définit deux espaces de noms
¤ Enveloppe SOAP :
http://schemas.xmlsoap.org/soap/envelope/
¤ Serialization SOAP:
http://schemas.xmlsoap.org/soap/encoding/
¨ Requête et Réponse ont la même structure
SOAP : En-tête
¨ Balise optionnelle identifié par
<namespace:Header>
¨ Quand il est présent, il doit être avant le Body
¨ Utilisé pour transmettre des informations
supplémentaires entre le consommateur et le
fournisseur du service
¨ Usages possibles
¤ Informations d’authentification
¤ Contexte d’une transaction
¤ Transiter des informations intermédiaires
SOAP : Corps
¨ Identifié par la balise <namespace:Body>
¨ Contient la réponse à l’appel d’une action du
service
¤ Une erreur <namespace:Fault>
¤ Réponse de l’action
¨ L’encodage est des informations est précisé par les
bindings du WSDL
SOAP : Requête
è Appeler les opérations d’un web service SOAP
<?xml version="1.0" encoding="UTF-8"?><S:Envelope xmlns:S="http://
schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://
schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<S:Body>
<ns2:sayHelloToTheWorld xmlns:ns2="http://
soap.bibliotheque.android.mbds.fds.edu.ht/"/>
</S:Body>
</S:Envelope>
Appel à la méthode sayHelloToTheWorld
sans paramètre
SOAP : Réponse
è Réponse du service à l’appel de la méthode
<?xml version="1.0" encoding="UTF-8"?><S:Envelope xmlns:S="http://
schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://
schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<S:Body>
<ns2:sayHelloToTheWorldResponse xmlns:ns2="http://
soap.bibliotheque.android.mbds.fds.edu.ht/">
<return>Hello World</return>
</ns2:sayHelloToTheWorldResponse>
</S:Body>
</S:Envelope>
Réponse du web service à l’appel de la
méthode sayHelloToTheWorld
SOAP : Requête
è Appeler les opérations d’un web service SOAP
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<S:Body>
<ns2:sayHelloTo xmlns:ns2="http://
soap.bibliotheque.android.mbds.fds.edu.ht/">
<name>Miage NTDP</name>
</ns2:sayHelloTo>
</S:Body>
</S:Envelope>
Appel à la méthode sayHelloTo du service
avec une valeur en paramètre
SOAP : Réponse
è Réponse du service à l’appel de la méthode
<?xml version="1.0" encoding="UTF-8"?><S:Envelope xmlns:S="http://
schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://
schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<S:Body>
<ns2:sayHelloToResponse xmlns:ns2="http://
soap.bibliotheque.android.mbds.fds.edu.ht/">
<return>Hello Miage NTDP !</return>
</ns2:sayHelloToResponse>
</S:Body>
</S:Envelope>
Réponse du web service à l’appel de la
méthode sayHelloTo
SOAP : Transport HTTP
¨ Structure d’une requête HTTP
¤ En-tête(http header)
¤ Corps (http body)
¨ Les messages SOAP sont encapsulés dans le corp de
la requête HTTP En tête HTTP
Corps HTTP
En tête SOAP
Corps SOAP
Enveloppe SOAP
SOAP : Prise en main
¨ Créer des services web SOAP en JAVA jax-ws et
Netbeans
Services Web RESTFul
Web Service REST
Définition
q Acronyme de REpresentational State Transfert
défini dans la thèse de Roy Fielding en 2000.
q REST n’est pas un protocole ou un format,
contrairement à SOAP, HTTP ou RCP, mais un style
d’architecture inspiré de l’architecture du web
fortement basé sur le protocole HTTP
q Il n’est pas dépendant uniquement du web et peut
utiliser d’autre protocoles que HTTP
Web Service REST
Ce qu’il est :
Ø Un système d’architecture
Ø Une approche pour construire une application
Ce qu’il n’est pas
Ø Un protocole
Ø Un format
Ø Un standard
REST è utilisation
Ø Utiliser dans le développement des applications
orientés ressources (ROA) ou orientées données
(DOA)
Ø Les applications respectant l’architecture REST sont
dites RESTful
REST è Fournisseurs
REST è Statistics
Statistique d’utilisation des services web REST et SOAP chez AMAZON
REST è Caractéristiques
¨ Les services REST sont sans états (Stateless)
¤ Chaque requête envoyée au serveur doit contenir
toutes les informations relatives à son état et est traitée
indépendamment de toutes autres requêtes
¤ Minimisation des ressources systèmes (pas de gestion de
session, ni d’état)
¨ Interface uniforme basée sur les méthodes HTTP
(GET, POST, PUT, DELETE)
¨ Les architectures RESTful sont construites à partir de
ressources uniquement identifiées par des URI(s)
Requêtes REST
¨ Ressources
¤ Identifiée
par une URI (
http://unice.fr/cursus/master/miage)
¨ Méthodes (verbes) permettant de manipuler les
ressources (identifiants)
¤ Méthodes HTTP : GET, POST, PUT, DELETE
¨ Représentation : Vue sur l’état de la ressource
¤ Formatd’échanges entre le client et le serveur (XML,
JSON, text/plain,…)
Ressources
q Une ressource est un objet identifiable sur le
système
è Livre, Catégorie, Client, Prêt
Une ressources n’est pas forcément un objet
matérialisé (Prêt, Consultation, Facture…)
q Une ressource est identifiée par une URI : Une URI
identifie uniquement une ressource sur le système
http://ntdp.miage.fr/bookstore/books/1 ressource
Clef primaire de la
dans la BDD
Méthodes (Verbes)
¨ Une ressource peut subir quatre opérations de
bases CRUD correspondant aux quatre principaux
types de requêtes HTTP (GET, PUT, POST, DELETE)
¨ REST s’appuie sur le protocole HTTP pour effectuer
ces opérations sur les objets
¤ CREATE è POST
¤ RETRIEVE è GET
¤ UPDATE è PUT
¤ DELETE è DELETE
Méthode GET
¨ La méthode GET renvoie une représentation de la
ressource tel qu’elle est sur le système
GET: http://ntdp.miage.fr/bookstore/books/1
Statut : 200
Message : OK
Client En-tête : …. Serveur
Représentation : XML, JSON, html,…
Méthode POST
¨ La méthode POST crée une nouvelle ressource sur le
système
POST: http://ntdp.miage.fr/bookstore/books
Corps de la requête
Représentation : XML, JSON, html,…
Client Statut : 201, 204 Serveur
Message : Create, No content
En-tête : …..
Méthode DELETE
¨ Supprime la ressource identifiée par l’URI sur le
serveur Identifiant de la
ressource sur le
serveur
DELETE: http://ntdp.miage.fr/bookstore/books/1
Client Statut : 200 Serveur
Message : OK
En-tête : …..
Méthode PUT
¨ Mise à jour de la ressource sur le système
Identifiant de la
ressource sur le
serveur
PUT: http://ntdp.miage.fr/bookstore/books/1
En-tête : …..
Corps de la requête : XML, JSON,…
Client Statut : 200 Serveur
Message : OK
En-tête : …..
Reflexions
¨ Que se passe t il
¤ sion fait de la lecture avec un POST ?
¤ Si on fait une mise à jour avec un DELETE ?
¤ Si on fait une suppression avec un PUT ?
è REST ne l’interdit pas
è Mais si vous le faites, votre application ne respecte
pas les exigences REST et donc n’est pas RESTFul
Représentation
Une représentation désigne les données échangées entre le client et le
serveur pour une ressource:
q HTTP GET è Le serveur renvoie au client l’état de la ressource
q PUT, POST è Le client envoie l’état d’une ressource au serveur
Peut être sous différent format :
¨ JSON
¨ XML
¨ XHTML
¨ CSV
¨ Text/plain
¨ …..
WADL
¨ Web Application Description Language
¨ Standard du W3C
¨ Permet de décrire les éléments des services
¤ Resource, Méthode, Paramètre, Réponse
¨ Permet d’interagir de manière dynamique avec les
applications REST
à Moins exploité que le WSDL pour les Services
SOAP
WADL
Rappel à JSON
JSON
JSON « JavaScript Obect Notation » est un format
d’échange de données, facile à lire par un humain et
interpréter par une machine.
Basé sur JavaScript, il est complètement indépendant des
langages de programmation mais utilise des conventions
qui sont communes à toutes les langages de
programmation (C, C++, Perl, Python, Java, C#, VB,
JavaScript,….)
Deux structures :
¨ Une collection de clefs/valeurs è Object
¨ Une collection ordonnée d’objets è Array
JSON
Objet
Commence par un « { » et se termine par « } » et
composé d’une liste non ordonnée de paire clefs/
valeurs. Une clef est suivie de « : » et les paires clef/
valeur sont séparés par « , »
{ "id": 51,
"nom": "Mathematiques 1", "resume":
"Resume of math ", "isbn": "123654",
"categorie":
{
"id": 2, "nom": "Mathematiques",
"description": "Description of
mathematiques "
},
"quantite": 42,
"photo": ""
}
JSON
ARRAY
Liste ordonnée d’objets commençant par « [« et se
terminant par « ] », les objets sont séparés l’un de
l’autre par « , ». [
{ "id": 51,
"nom": "Mathematiques 1",
"resume": "Resume of math ",
"isbn": "123654",
"quantite": 42,
"photo": ""
},
{ "id": 102,
"nom": "Mathematiques 1",
"resume": "Resume of math ",
"isbn": "12365444455",
"quantite": 42,
"photo": ""
}
]
JSON
Value
Un objet peut être soit un string entre « ""» ou un
nombre (entier, décimal) ou un boolean (true, false)
ou null ou un objet.
Services Web étendus VS REST
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-
ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<S:Body> <ns2:hello xmlns:ns2="http://
services.bibliotheque.ntdp.miage.unice.fr/">
<name>Miage NTDP</name>
</ns2:hello>
</S:Body>
</S:Envelope>
SOAP
Client Serveur
http://localhost:8080/Bibliotheque/webresources/category/Miage%20NTDP
REST
Client Serveur
Services Web étendus VS REST
SOAP
è Avantages
è Standardisé
è Interopérabilité
è Sécurité (WS-Security)
è Inconvénients
è Performances (enveloppe SOAP supplémentaire)
è Complexité, lourdeur
è Cible l’appel de service
Services Web étendus VS REST
REST
è Avantages
è Simplicité de mise en œuvre
è Lisibilité par un humain
è Evolutivité
è Repose sur les principes du web
è Représentations multiples (XML, JSON,…)
è Inconvénients
è Sécurité restreinte par l’emploi des méthodes HTTP
è Cible l’appel de ressources
WADL
è Web Application Definition Language est un
langage de description des services REST au format
XML. Il est une spécification di W3C initié par SUN
(www.w.org/Submission/wadl)
è Il décrit les éléments à partir de leur type
(Ressources, Verbes, Paramètre, type de requête,
Réponse)
è Il fournit les informations descriptives d’un service
permettant de construire des applications clientes
exploitant les services REST.
Partie 2
Développer des Web Services REST avec JAVA
Session 1
JAX-RS
¨ Acronyme de Java API for RestFul Web Services
¨ Version courante 2.0 décrite par JSR 339
¨ Depuis la version 1.1, il fait partie intégrante de la
spécification Java EE 6
¨ Décrit la mise en œuvre des services REST web coté
serveur
¨ Son architecture se repose sur l’utilisation des
classes et des annotations pour développer les
services web
JAX-RS è Implémentation
¨ JAX-RS est une spécification et autour de cette
spécification sont développés plusieurs
implémentations
¤ JERSEY : implémentation de référence fournie par
Oracle ( http://jersey.java.net )
¤ CXF : Fournie par Apache ( http://cfx.apache.org )
¤ RESTEasy : fournie par JBOSS
¤ RESTLET : L’un des premiers framework implémentant
REST pour Java
JERSEY
¨ Version actuelle 2.3.1 implémentant les
spécifications de JAX-RS 2.0
¨ Intégré dans Glassfish et l’implémentation Java EE
(6,7)
¨ Supportés dans Netbeans
JAX-RS : Développement
¨ Basé sur POJO (Plain Old Java Object) en utilisant
des annotations spécifiques JAX-RS
¨ Pas de modifications dans les fichiers de
configuration
¨ Le service est déployé dans une application web
¨ Pas de possibilité de développer le service à partir
d’un WADL contrairement à SOAP
¨ Approche Bottom/Up
¤ Développer et annoter les classes
¤ Le WADL est automatiquement généré par l’API
Annotation JAX-RS
La spécification JAX-RS dispose d’un ensemble
d’annotation permettant d’exposer une classe java
dans un services web :
q @Path
q @GET, @POST, @PUT, @DELETE
q @Produces, @Consumes
q @PathParam
Modéliser les URIs
URIs sont déterminés par l’annotation @Path
q Permet d’exposer une classe dans le WS
q Définit la racine des ressources (Root Racine
Ressources)
q Sa valeur correspond à l’URI relative de la
ressource Adresse du serveur Ressource
@Path("category")
public class CategoryService { http://localhost:8080/Bibliotheque/webresources/category
……
}
Contexte de
Port l’application
URIs des méthodes
q @Path peut être utilisée pour annoter des méthodes
d’une classe
q L’URI résultante est la concaténation entre le valeur
de @Path de la classe et celle de la méthode
@Path("category")
public class CategoryFacade {
@GET
@Produces({MediaType.APPLICATION_XML,
MediaType.APPLICATION_JSON})
@Path("test")
public String hello()
{
return "Hello World!";
}
..
}
http://localhost:8080/Bibliotheque/webresources/category/test
URIs dynamiques
q La valeur définie dans l’annotation @Path n’est
forcément un constante, elle peut être variable.
q Possibilité de définir des expressions plus
complexes, appelées Template Parameters
q Les contenus complexes sont délimités par « {} »
q Possibilité de mixer dans la valeur @Path des
expressions régulières
@GET
@Consumes ({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces ({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path( "hello/{nom}")
public String hello (@PathParam("nom") String nom){
return "Hello " + nom;
}
http://localhost:8080/Bibliotheque/webresources/category/hello/Miage
URIs dynamiques
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("coucou/{nom}/{prenom}")
public String hello(@PathParam("nom") String nom,
@PathParam("prenom") String prenom) {
return "Hello " + nom + " " + prenom;
}
GET http://localhost:8080/Bibliotheque/webresources/category/coucou/Miage/NTDP
@GET
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("{id}")
public Categorie find (@PathParam("id") Long id) {
return super.find(id);
GET http://localhost:8080/Bibliotheque/webresources/category/1
@GET, @POST, @PUT, @DELETE
¨ Permettent de mapper une méthode à un type de requête HTTP
¨ Ne sont utilisables que sur des méthodes
¨ Plusieurs méthodes peuvent avoir le même chemin, le mapping uri/méthode est fait
automatiquement par JAX-RS en fonction du type de la requête
http://localhost:8080/Bibliotheque/webresources/category/test
@GET
@Produces({MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML})
@Path("hello/{nom}/{prenom}")
@POST
public String hello(@PathParam("nom") String
@Produces({MediaType.APPLICATION_JSON,
nom, @PathParam("prenom") String prenom) { MediaType.APPLICATION_XML})
return "GET " + nom + " " + prenom; @Path("hello/{nom}/{prenom}")
} public String helloPost(@PathParam("nom")
String nom, @PathParam("prenom") String prenom) {
return "POST " + nom + " " + prenom;
}
[GET/POST] http://localhost:8080/Bibliotheque/webresources/hello/Miage/NTDP
@GET, @POST, @PUT, @DELETE
¨ Les opérations CRUD sur les ressources sont
réalisées au travers des méthodes de la requête
HTTP
/books
GET : Liste des livres
POST : Créer un nouveau livre
GET, POST
PUT, DELETE /books/{id}
GET : Livre identifié par l’id
PUT: Mis à jour du livre identifié par id
DELETE : Supprimer le livre identifié par id
Outils de test
¨ Il existe de nombreux outils en ligne permettant de
tester les services Web REST
¨ Certains sont disponibles sous forme d’extansion
que vous pouvez installer dans les navigateurs
¤ RestConsole
¤ PostMan
A vos marques !