Introduction aux Services Web RESTful
Introduction aux Services Web RESTful
M. F. Zhani 2
Évolution du Web
M. F. Zhani 3
Évolution du Web
Caractéristiques
Les usagers peuvent produire et consommer des données
Le Web est une plateforme de participation
Les utilisateurs peuvent faire exécuter des applications logicielles
entièrement à travers un navigateur
Les données et les services peuvent être combinés pour créer des
services composés
M. F. Zhani 4
Évolution du Web
Web 3.0 I have a dream for the Web [in which
computers] become capable of analyzing all
Permettre aux utilisateurs mais the data on the Web – the content, links, and
surtout aux machines de trouver,
transactions between people and computers.
partager et combiner l'information
plus facilement A "Semantic Web", which makes this possible,
Utilise le Web sémantique: has yet to emerge, but when it does, the day-
to-day mechanisms of trade, bureaucracy and
“The Semantic Web provides a common our daily lives will be handled by machines
framework that allows data to be talking to machines.
shared and reused across application,
enterprise, and community boundaries” The "intelligent agents" people have touted
[W3C, 2011] for ages will finally materialize.
Tim Berners-Lee, 1993
Offre un meilleur support pour la
Inventor of the World Wide Web
coopération entre machines et
Director of the World Wide Web Consortium (W3C)
utilisateurs
M. F. Zhani 5
Évolution du Web
Web 1.0 Web 2.0 et 3.0
– Web Humain – Web programmable
– HTML – XML, JSON
– Client/serveur – Pair-à-paire
– Lecture des données – Lecture/écriture
– Pages web personelles/ – blogs, sites dynamiques, flux
professionelles temps réels
– Possession d’information – Partage d’information
– Communication Machine
vers Machine
➔ Services web
M. F. Zhani 6
Plan du chapitre
• Evolution du Web
• Web Services et Cloud
• Resource-Oriented Architecture (ROA)
• Contraintes du REpresentational State Transfer
(REST)
• Création d’un service basé sur REST
• Outils de développement
• Protocole OAuth
M. F. Zhani 7
Web Services
Le terme « Web services » est une architecture logicielle permettant à des
appareils ou applications de communiquer à travers un réseau IP
Un service Web est un service offert par une machine à une machine.
Utilise les technologies Web (principalement http)
Utilise fichier en format lu par les machines (XML ou JSON)
M. F. Zhani 10
Web Services – Architectures
Deux architectures de Web Services existents :
M. F. Zhani 12
Resource-Oriented Architecture
(ROA)
Un style d’architecture pour concevoir un système informatique ainsi que la
communication entre ses composants
Objectif: comment développer une architecture orientée ressource?
ROA comprend un ensemble de
Concepts : Ressources, Identifiants de ressources, Représentations de ressources, Liens
entre ressources, Interface http pour accéder et manipuler l’état d’une ressource
Contraintes à respecter (appelées contraintes RESTful): un système RESTful est un
système conforme à ces contraintes
ROA est défini autour du concept de « ressource »: tout objet qui peut être nommé
Une ressource: document, une information (par ex. météo du jour), le résultat de
l’exécution d'un algorithme
Une collection de ressources (une liste): une ressource peut contenir une sous-collection
de ressources (par ex., une classe contient des étudiants)
M. F. Zhani 13
Resource-Oriented Architecture
(ROA)
Identifiant de ressource : une ressource est identifiée d’une façon unique grâce à un URI
(Unique Resource Identifier)
Exemples: Parc informatique avec des équipements, chaque équipement héberge des scripts,
utilisateurs
http://api.example.ca/device-management/managed-devices ➔ liste des équipements
http://api.example.ca/device-management/managed-devices/{id} ➔ un équipement avec l’identifiant {id}
http://api.example.ca/device-management/managed-devices/{id}/scripts ➔ liste des scripts pour équipement
dont l’id est {id}
http://api.example.ca/device-management/managed-devices/{id}/scripts/{ids} ➔ script {ids} pour équipement {id}
http://api.example.ca/user-management/users/ ➔ liste des utilisateurs
http://api.example.ca/user-management/users/{id} ➔ l’utilisateur dont l’id est {id}
Meilleures pratiques :
Utiliser un nom pour la ressource (pas un verbe)
Les URIs devraient avoir une structure et devraient varier de façon prévisible
Utilisez une barre oblique (/) pour indiquer une relation hiérarchique
Filtrage et tri pour une liste de ressources : utiliser les paramètres (query)
http://api.example.com/device-management/managed-devices
http://api.example.com/device-management/managed-devices?region=USA
http://api.example.com/device-management/managed-devices?region=USA&brand=XYZ
http://api.example.com/device-management/managed-devices?region=USA&brand=XYZ&sort=purchase-date
M. F. Zhani 14
Resource-Oriented Architecture
(ROA)
Exemple :
Resource : une personne (Jean)
Représentation : Nom, adresse, numéro de téléphone
Représentation: Nom, prénom, classe, notes
M. F. Zhani 15
REpresentational State Transfer
(REST)
Rest: Un style d'architecture d’applications Web développé en parallèle avec
HTTP 1.1 (RFC 2616)
Proposé pour la 1ère fois par Roy Fielding dans sa thèse de doctorat en 2000 :
"Architectural Styles and the Design of Network-based Software Architectures”
Objectifs : développer des applications web bien conçues
Un réseau de page web (état) où l’utilisateur navigue d’une page à une autre page
(transition d’état) à travers des liens hypertextes.
Les avantages d’appliquer ces contraintes : performance, mise à l’échelle (scalability),
facilité de maintenance, portabilité, fiabilité
REST n'est pas un standard, mais utilise des technologies et des standards
existants. Par exemple : Architecture client/serveur, HTTP, URI, Format XML,
HTML, JSON
M. F. Zhani 16
Contraintes REST
Contraintes
1. Client/Serveur
2. Cacheable
3. Code On Demand
4. Adressabilité
5. Statelessness (sans état)
6. Connectivité (connectedness)
7. Interface uniforme
M. F. Zhani 17
Contraintes du REST
(1) Client/Serveur
M. F. Zhani 18
Contraintes du REST
(2) Cacheable
La réponse doit indiquer si elle est cacheable ou non (implicite,
explicite).
➔ Moins d’interactions
➔ Meilleure performance
M. F. Zhani 19
Contraintes du REST
(3) Code On Demand
Exemples:
Java applets
Javascript
➔ Meilleure extensibilité
M. F. Zhani 20
Contraintes du REST
(4) Adressabilité
M. F. Zhani 21
Contraintes du REST
(5) Statelessness
Avantages :
Moins de complexité au niveau du serveur
Pas d’ordre particulier pour les actions
Facilite l'équilibrage de charge (load balancing)
Facilite l'accès à toute ressource (pour le client)
M. F. Zhani 22
Contraintes du REST
(5) Statelessness
http://andreadekker.com/wp-content/uploads/2010/08/Google-Search-Engine.jpg
M. F. Zhani 24
Contraintes du REST
(7) Interface uniforme
Interface: chaque ressource est accessible et manipulable via une interface
uniforme : les méthodes du protocoles HTTP (par ex., GET, POST, PUT, DELETE)
Avec PUT :
PUT: http://www.example.com/users/users1
Créer/mettre à jour user1: http://www.example.com/users/users1
Avec POST :
POST: http://www.example.com/users/
utilisateur: http://www.example.com/users/user1547
M. F. Zhani 27
Contraintes du REST
(7) Interface uniforme
Tolérance aux pannes des APIs
Que se passe-t-il lorsqu’on on appelle chacune des méthodes http
plusieurs fois consécutives (par exemple, lorsque la réponse est
perdue) ?
GET ➔ idempotente
POST ➔ non idempotente
PUT ➔ idempotente
DELETE ➔ idempotente
HEAD ➔ idempotente
OPTIONS ➔ idempotente
➔ Il faut s’assurer que de telles cas ne génèrent pas de problèmes
*Idempotence: une méthode est idempotente si elle peut être
exécutée plusieurs fois sans conséquence
M. F. Zhani 28
Plan du chapitre
• Evolution du Web
• Resource-Oriented Architecture (ROA)
• Contraintes du REpresentational State Transfer
(REST)
• Création d’un service basé sur REST
• Outils de développement
• Protocole OAuth
M. F. Zhani 29
Création d’un service basé sur REST
1. Déterminez l'ensemble des données
2. Diviser l'ensemble des données en ressources
Pour chaque ressource :
3. Nommer la ressource via un URI
4. Exposer un sous-ensemble de l'interface uniforme
5. Concevoir les représentations acceptées du client
6. Concevoir les représentations servies au client
7. Intégrer cette ressource avec les autres ressources existantes, en utilisant des liens
hypermédias
8. Considérons le cours typique des événements: qu’est ce qui est censé se passer ?
9. Considérons les conditions d'erreur : qu’est ce qui pourrait mal tourner ?
M. F. Zhani 30
Exemple Illustratif :
Service de gestion de conférences
Créer un service qui permet aux utilisateurs de :
Créer une conférence
Arrêtez une conférence
Changer les médias (par ex., audio, vidéo) pour une conférence
Obtenir l’état d’une conférence
Ajouter des participants à une conférence
Supprimer des participants d'une conférence
Changer les médias pour un participant
Obtenir les média d’un participant
M. F. Zhani 31
Exemple Illustratif
M. F. Zhani 32
Exemple Illustratif
M. F. Zhani 33
Exemple Illustratif
4. Exposer un sous-ensemble de l'interface uniforme
Resource Operation Action HTTP Corps Corps
CRUD Requête Réponse
Conférence Create: établir POST: http://confexample.com/ OUI OUI
une
conférence
Read: GET: http://confexample.com/{confId} NON OUI
Obtenir le
statut de
conférence
Update: PUT: http://confexample.com/{confId} OUI NON
Changer les
médias pour
une
conférence
Delete: DELETE: NON NON
terminer une http://confexample.com/{confId}
conférence
M. F. Zhani 34
Exemple Illustratif
Resource Operation Action HTTP Corps Corps
CRUD Requête Réponse
Participants Create: Ajouter POST: OUI OUI
un (des) http://confexample.com/{confId}/participants
participant (s)
M. F. Zhani 35
Exemple Illustratif
5-6-7. Concevoir les représentations acceptées
ou servies par le client
Corps de la requête pour créer une conférence (POST):
<Participants>
<Participant>[email protected]</Participant>
<Participant>[email protected]</Participant>
<Participant>[email protected]<Participant>
</Participants>
<Media>audio</Media>
M. F. Zhani 36
Exemple Illaustratif
Corps de la réponse pour la requête d’obtention de l’état d’une
conférence (GET)
<Participants>
<Participant media=“video”>[email protected]</Participant>
<Participant>[email protected]</Participant>
<Participant>[email protected]<Participant>
</Participants>
<Media>audio</Media>
M. F. Zhani 37
Exemple Illustratif
Corps de la requête d’ajout de participants (PUT):
<Participants>
<Participant media=“audio”>[email protected]</Participant>
<Participant media=“video”>[email protected]</Participant>
</Participants>
<Participant media=“audio”>[email protected]</Participant>
<Media>video</Media>
M. F. Zhani 39
Exemple Illustratif
8. Ce qui est censé se passer?
Alice
Créer une REST Client
Conf App
REST Server
conférence Participant
1 : POST(http://www.confexample.com)
2 : 202 Accepted(http://www.confexample.com/[email protected])
3 : INVITE
4 : OK
5 : ACK
6 : 200 OK
7 : GET(http://www.conference.example.com/[email protected])
8 : 200 OK
M. F. Zhani 40
Exemple Illustratif
Alice Conf App Bob
REST Client
REST Server
participant <Participants>
<Participant media=“video”>[email protected]</Participant>
</Participants>
2 : 202 Accepted()
3 : INVITE
4 : OK
5 : ACK
6 : 200 OK
<Participants>
<Participant>
<uri>[email protected]</uri>
<link>http://confexample.com/{confId}/participants/[email protected]</link>
</Participant>
</Participants>
M. F. Zhani 41
Exemple Illustratif
9. Ce qui pourrait mal tourner?
Conférence
M. F. Zhani 42
Exemple Illustratif
Participant(s)
Opération Server➔ Client Problème
Succès: 200 OK • La requête reçue n'est pas correcte
Create (e.g., corps mal formaté)
Echec: 400 Bad Request
(POST)
Echec: 404 Not Found • La conférence cible n'existe pas
Succès: 200 OK • La conférence cible n'existe pas
Read (GET)
Echec: 404 Not Found • Le participant cible n'existe pas
Update Succès: 200 OK • La requête reçue n'est pas correcte
(PUT) Echec: 400 Bad Request • La conférence cible n'existe pas
Echec: 404 Not Found • Le participant cible n'existe pas
Delete Succès: 200 OK • La conférence cible n'existe pas
(DELETE) Echec: 404 Not Found • Le participant cible n'existe pas
M. F. Zhani 43
Plan du chapitre
• Web Services et Cloud
• Evolution du Web
• Resource-Oriented Architecture (ROA)
• Contraintes du REpresentational State Transfer
(REST)
• Création d’un service basé sur REST
• Outils de développement
• Protocole OAuth
M. F. Zhani 44
Outils de développement
Techniques
Ajax : envoi et réception de requêtes entre une application web et un
serveur
HTTP Servlet : génère des réponses aux requêtes
Application Programming Interface (API)
JAX-RS: The Java API for RESTful Web Services
Resettle : Open source RESTful web API framework for the Java platform.
XMLHTTPRequest API : API qui fournit des fonctionnalités de client pour
transférer des données entre le client et le serveur.
Quelques outils
HttpRequester, Postman : permettent d’envoyer des requêtes HTTP (par
ex., GET, POST, DELETE) et d’analyser les réponses.
M. F. Zhani 45
Exemples de service web basés sur REST
M. F. Zhani 46
Plan du chapitre
• Web Services et Cloud
• Evolution du Web
• Resource-Oriented Architecture (ROA)
• Contraintes du REpresentational State Transfer
(REST)
• Création d’un service basé sur REST
• Outils de développement
• Protocole OAuth
M. F. Zhani 47
OAUTH 2.0
Un protocole permettant à une tierce partie (une application) d’avoir
un accès limité aux ressources d’un utilisateur qui sont localisées dans
un serveur de ressources (RFC 6749)
L’application n’aura jamais besoin de connaître le mot
de passe mais utilise plutôt un jeton d’accès (access token)
Toute la procédure se base sur HTTP
Exemple : instagram voudrait accéder aux photos d’un utilisateur
de facebook
Application : instagram
Serveur d’autorisation
Le client est l’application
qui veut accéder aux Le serveur d'autorisation vérifie
données d’un utilisateur l'identité de l'utilisateur puis
dans un serveur de émet des jetons d'accès (access
ressources token) au client.
M. F. Zhani 50
OAUTH 2.0 - Implémentation
M. F. Zhani 51
OAUTH 2.0 - Implémentation
M. F. Zhani 52
Plus d’informations ?
M. F. Zhani 53
Bibliographie
[1] Fatna Belqasmi, Chunyan Fu, Roch Glitho, RESTful Web Services for
Service Provisioning in Next Generation Networks: A Survey, IEEE
Communications Magazine, December 2011
[2] L. Richardson and S. Ruby, “RESTful Web Services”, O’Reilly &
Associates, ISBN 10: 0-596-52926-0, May 2007
[3] D. Fensel et al., ‘Web 2.0 services’, STI-INNSBRUCK, 2010
[4] R. T. Fielding, ‘Architectural Styles and the Design of network-based
software architectures’, Ph.D. thesis, 2000
[5] R. L. Costello, ‘Building Web services the Rest Way’, 2006
M. F. Zhani 54
Rappel sur HTTP
55
Message de requête HTTP
❑ Deux types de messages HTTP: requête, réponse
❑ message de requête HTTP :
ASCII (format lisible par les humains)
Ligne de requête
(commandes GET, GET /somedir/page.html HTTP/1.1\r\n
POST, HEAD) Host: www.someschool.edu \r\n
User-agent: Mozilla/4.0\r\n
Lignes de l’entête Connection: close\r\n
Accept-language:fr\r\n
\r\n
Carriage return
(extra carriage return, line feed)
et line feed
pour indiquer
la fin du message
M. F. Zhani 56
Message de requête HTTP : format général
M. F. Zhani 57
Envoie d’un formulaire d’entrée
Méthode POST :
www.somesite.com/animalsearch?monkeys&banana
M. F. Zhani 58
Types de méthodes
HTTP/1.0 HTTP/1.1
M. F. Zhani 59
Message de réponse HTTP
200 OK
Requête réussie, objet requis viendra plus tard dans le msg
M. F. Zhani 61