SlideShare une entreprise Scribd logo
1  sur  26
Télécharger pour lire hors ligne
http://roma2017.drupalday.it
http://www.bmeme.com
http://www.bmeme.com
Adriano Cori
• drupal.org: aronne
• github.com: Fatal-Error
• twitter: @coriadriano
• email: adriano.cori@bmeme.com
return shuffle([
"programmazione",
"famiglia",
"videogames",
"calcio",
]);
HTTP
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
Adriano Cori, @bmeme
DrupalDay Roma
3 Marzo 2017
CLIENT MANAGER
HTTP CLIENT MANAGER
“L'HyperText Transfer Protocol (HTTP) è un protocollo a livello
applicativo usato come principale sistema per la trasmissione
d'informazioni sul web ovvero in un'architettura tipica client-
server.”- https://it.wikipedia.org/wiki/Hypertext_Transfer_Protocol
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP REQUEST
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
• POST
• GET
• PUT, PATCH
• DELETE
• OPTIONS
• HEAD
• TRACE
• CONNECT
> Request Method
• CREATE
• RETRIEVE
• UPDATE
• DELETE
> Request URI
Lo uniform resource identifier indica
l'oggetto della richiesta
> Request Header
• Host
• User-Agent
• Accept
HTTP RESPONSE
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
• 200
• 301
• 302
• 307
• 400
• 404
• 500
• 505
> Response Status
Ok
Moved Permanently
Found
Temporary Redirect
Bad Request
Not Found
Internal Server Error
HTTP Version Unsupported
> Response body
Contiene il contenuto della
risposta
> Response Header
• Date
• Content-Type
• Cache-Control
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
“REpresentational State Transfer (REST) è un tipo di architettura
software per i sistemi di ipertesto distribuiti come il World Wide
Web.”- https://it.wikipedia.org/wiki/Representational_State_Transfer
“REST defines a set of architectural principles by which you can
design Web services that focus on a system's resources, including
how resource states are addressed and transferred over HTTP by a
wide range of clients written in different languages.”
- https://www.ibm.com/developerworks/webservices/library/ws-restful
/**

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*/
@see DrupalsparkfabrikPaoloPustorino::restInPieces()
REST SERVICE
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
> HTTP Response
HTTP/1.1 200 OK

Content-Type: application/json; charset=UTF-8


[
{
"id": 1,
"title": "Ma che bella notizia",
"body": "Lorem ipsum non passa mai di moda",
"date": "2017-03-03 10:15:32”
},
{
"id": 2,
"title": "Inizia il talk di @aronne",
"body": "Lorem ipsum come se piovesse",
"date": "2017-03-03 10:02:54”
}
]
GET /api/news?date=2017-03-03 HTTP/1.1
Host: example.com
User-Agent: curl/7.43.0
Accept: application/json
> HTTP Request
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
“An HTTP client uses HTTP to connect to a web server over the
Internet to transfer documents or other data. The most well known
types of HTTP Clients include web browsers.”- https://en.wikipedia.org/wiki/
Category:Hypertext_Transfer_Protocol_clients
Cosa ci mette a disposizione Drupal 8?
Drupal::httpClient()
public static function httpClient() {
return static::getContainer()->get('http_client');
}
http_client:

class: GuzzleHttpClient

factory: http_client_factory:fromOptions
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
$news = Drupal::httpClient()->request(

'GET',

'http://api.example.com/news',

['date' => '2017-03-03']

);
“Ahah..ma come Guzzle se fa dico io”
Alternative?
ALTERNATIVE
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
Creare una classe che faccia da wrapper al Drupal::httpClient()
• Memorizzare l’host tanto per cominciare
• Creare dei metodi ad hoc per ogni Request
• Validazione dei parametri
• Design pattern a piacere :)
• Riusabilità del codice
• …
e poi un bel giorno….
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
REFACTORING
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
Creare una classe astratta che faccia da bla bla bla…
• Programmazione orientata agli insulti
• Il nuovo codice va ritestato
• la tua ragazza ti lascia
• il corvo si sbagliava riguardo alla pioggia
• belle sbuffate
• io manco ce volevo veni’
• e mettemocela n’altra if…
• AggileGiggi me spiccia casa
ma poi alla fine….
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
REFACTORING
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
Come si potrebbe migliorare ancora il nostro codice?
• Rendendolo (se non lo si era già fatto) il più astratto possibile
• Rimuovendo dal codice info relative agli endpoint, risorse e 

parametri, spostandole invece su dei file di configurazione
• cancellandolo…
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
Http Client Manager introduces a new Guzzle based plugin which
allows you to manage HTTP clients using Guzzle Service Descriptions
via JSON files, in a simple and efficient way:
"Service descriptions define web service APIs by documenting each
operation, the operation's parameters, validation options for each
parameter, an operation's response, how the response is parsed, and
any errors that can be raised for an operation. Writing a service
description for a web service allows you to more quickly consume a
web service than writing concrete commands for each web service
operation.”
You will no longer need to write down Http services calls each times
specifying endpoints and parameters in a totally decentralized way.
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
> Http Services Api definition via *.http_services_api.yml file
example_services:
title: "Example Services - posts API"
api_path: "src/api/example_services.json"
base_url: "http://api.example.com"
auth_services:
title: "Another Example Services - auth API"
api_path: "src/api/auth_services.json"
base_url: “http://auth.services.com"
> Overridable Services Api definition via settings.php file
$settings['http_services_api']['example_services'] = [
'title' => 'Example Services - posts API (Development)',
'base_url' => 'http://api.example.dev',
];
> Ad Hoc client definition via *.services.yml file
services:
example_api.http_client:
parent: http_client_manager.client_base
arguments: ['example_services']
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
> src/api/example_services.json
{
"name": "ExampleServicesApi",
"apiVersion": "2016-07-29",
"description": "Example Services API descriptions.",
"includes" : [
"resources/posts.json"
]
}
> src/api/resources/posts.json
{
"operations": {
"FindPosts": {
"httpMethod": "GET",
"uri": "posts/{postId}",
"summary": "Find posts",
"parameters": {
"postId": {
"location": "uri",
"description": "Filter posts by id",
"required": false,
"type": "string"
}
}
},
"models": {}
}
HTTP SERVICE DESCRIPTIONS
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
> Multiple ways to instantiate http clients
// Client instantiation via http_client_manager service factory method.
$client = Drupal::service('http_client_manager.factory')->get('example_services');
// Client instantiation via service.
$client = Drupal::service(‘example_api.http_client');
> Multiple ways to execute http requests
// Call method usage.
$latestPosts = $client->call('FindPosts', ['limit' => '10', 'sort' => 'desc']);
// Magic method usage.
$latestPosts = $client->findPosts(['limit' => '10', 'sort' => 'desc']);
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
You can also create and store (bookmark) predefined requests via web UI as
Configuration Entities (exportable via Configuration Manager), and execute
them from your code in this way:
// Http Config Request usage via Config Entity static method.
$latestPosts = HttpConfigRequest::load('find_posts')->execute();
// Http Config Request usage via entity type manager.
$latestPosts = $this->entityTypeManager()
->getStorage('http_config_request')
->load('find_posts')
->execute();
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
/**
* Class HttpEventSubscriber.
*/
class HttpEventSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
static function getSubscribedEvents() {
return [
'request.before_send' => array('onRequestBeforeSend', -1000)
];
}
/**
* Request before-send event handler
*
* @param Event $event
* Event received
*/
public function onRequestBeforeSend(Event $event) {
// your code goes here…
}
}
CONCLUSIONI
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
HTTP CLIENT MANAGER
HTTP Client Manager in cosa ci aiuta?
• Ad evitare la dispersione del codice centralizzandone l’utilizzo
• Ad evitare di scrivere altro codice in favore di un riutilizzo delle 

descrizioni dei servizi
• A risolvere un problema comune proponendosi quindi come un

nuovo standard per la gestione delle sorgenti e per la

presentazione di dati nelle istanze Drupal che consumano servizi
HTTP CLIENT MANAGER
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
LIVE DEMO
QUESTIONS
& ANSWERS
HTTP CLIENT MANAGER
DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
LIVE DEMO
QUESTIONS
& ANSWERS

Contenu connexe

Tendances

Content-centric architectures - case study : Apache Sling
Content-centric architectures - case study : Apache SlingContent-centric architectures - case study : Apache Sling
Content-centric architectures - case study : Apache Sling
Fabrice Hong
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8
Ovadiah Myrgorod
 

Tendances (20)

Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
How we maintain 200+ Drupal sites in Georgetown University
How we maintain 200+ Drupal sites in Georgetown UniversityHow we maintain 200+ Drupal sites in Georgetown University
How we maintain 200+ Drupal sites in Georgetown University
 
Java One Presentation - Ruby on Rails meets Enterprise
Java One Presentation - Ruby on Rails meets EnterpriseJava One Presentation - Ruby on Rails meets Enterprise
Java One Presentation - Ruby on Rails meets Enterprise
 
Ruby on Rails Meets Enterprise Applications
Ruby on Rails Meets Enterprise ApplicationsRuby on Rails Meets Enterprise Applications
Ruby on Rails Meets Enterprise Applications
 
Create a Varnish cluster in Kubernetes for Drupal caching - DrupalCon North A...
Create a Varnish cluster in Kubernetes for Drupal caching - DrupalCon North A...Create a Varnish cluster in Kubernetes for Drupal caching - DrupalCon North A...
Create a Varnish cluster in Kubernetes for Drupal caching - DrupalCon North A...
 
Plack basics for Perl websites - YAPC::EU 2011
Plack basics for Perl websites - YAPC::EU 2011Plack basics for Perl websites - YAPC::EU 2011
Plack basics for Perl websites - YAPC::EU 2011
 
RESTful web apps with Apache Sling - 2013 version
RESTful web apps with Apache Sling - 2013 versionRESTful web apps with Apache Sling - 2013 version
RESTful web apps with Apache Sling - 2013 version
 
Effective Web Application Development with Apache Sling
Effective Web Application Development with Apache SlingEffective Web Application Development with Apache Sling
Effective Web Application Development with Apache Sling
 
Content-centric architectures - case study : Apache Sling
Content-centric architectures - case study : Apache SlingContent-centric architectures - case study : Apache Sling
Content-centric architectures - case study : Apache Sling
 
HTTPS + Let's Encrypt
HTTPS + Let's EncryptHTTPS + Let's Encrypt
HTTPS + Let's Encrypt
 
Scalable talk notes
Scalable talk notesScalable talk notes
Scalable talk notes
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8
 
HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & sockets
 
Developing OpenResty Framework
Developing OpenResty FrameworkDeveloping OpenResty Framework
Developing OpenResty Framework
 
Apache Jackrabbit Oak - Scale your content repository to the cloud
Apache Jackrabbit Oak - Scale your content repository to the cloudApache Jackrabbit Oak - Scale your content repository to the cloud
Apache Jackrabbit Oak - Scale your content repository to the cloud
 
Mehr Performance für WordPress - WordCamp Köln
Mehr Performance für WordPress - WordCamp KölnMehr Performance für WordPress - WordCamp Köln
Mehr Performance für WordPress - WordCamp Köln
 
Getting Distributed (With Ruby On Rails)
Getting Distributed (With Ruby On Rails)Getting Distributed (With Ruby On Rails)
Getting Distributed (With Ruby On Rails)
 
Web Development with NodeJS
Web Development with NodeJSWeb Development with NodeJS
Web Development with NodeJS
 
Common Pitfalls for your Drupal Site, and How to Avoid Them
Common Pitfalls for your Drupal Site, and How to Avoid ThemCommon Pitfalls for your Drupal Site, and How to Avoid Them
Common Pitfalls for your Drupal Site, and How to Avoid Them
 

En vedette

En vedette (20)

[drupalday 2017] - Accessibilità Web: Finalità, metodologie e strumenti.
[drupalday 2017] - Accessibilità Web: Finalità, metodologie e strumenti.[drupalday 2017] - Accessibilità Web: Finalità, metodologie e strumenti.
[drupalday 2017] - Accessibilità Web: Finalità, metodologie e strumenti.
 
[drupalday2017] - Cloud e integrazione per la PA: la sfida dell'Open Source t...
[drupalday2017] - Cloud e integrazione per la PA: la sfida dell'Open Source t...[drupalday2017] - Cloud e integrazione per la PA: la sfida dell'Open Source t...
[drupalday2017] - Cloud e integrazione per la PA: la sfida dell'Open Source t...
 
[drupalday2017] - Open Data con Drupal nella PA: considerazioni su licensing ...
[drupalday2017] - Open Data con Drupal nella PA: considerazioni su licensing ...[drupalday2017] - Open Data con Drupal nella PA: considerazioni su licensing ...
[drupalday2017] - Open Data con Drupal nella PA: considerazioni su licensing ...
 
[drupalday2017] - Behat per Drupal: test automatici e molto di più
[drupalday2017] - Behat per Drupal: test automatici e molto di più[drupalday2017] - Behat per Drupal: test automatici e molto di più
[drupalday2017] - Behat per Drupal: test automatici e molto di più
 
[drupalday2017] - DRUPAL per la PA: il modello della Trasparenza di Sapienza
[drupalday2017] - DRUPAL per la PA: il modello della Trasparenza di Sapienza[drupalday2017] - DRUPAL per la PA: il modello della Trasparenza di Sapienza
[drupalday2017] - DRUPAL per la PA: il modello della Trasparenza di Sapienza
 
[drupalday2017] - Drupal 4 Stakeholders
[drupalday2017] - Drupal 4 Stakeholders[drupalday2017] - Drupal 4 Stakeholders
[drupalday2017] - Drupal 4 Stakeholders
 
[drupalday2017] - Drupal & Patternlab: un nuovo approccio al theming
[drupalday2017] - Drupal & Patternlab: un nuovo approccio al theming[drupalday2017] - Drupal & Patternlab: un nuovo approccio al theming
[drupalday2017] - Drupal & Patternlab: un nuovo approccio al theming
 
[drupalday2017] - Decoupled frontend con Drupal 8 e OpenUI 5
[drupalday2017] - Decoupled frontend con Drupal 8 e OpenUI 5[drupalday2017] - Decoupled frontend con Drupal 8 e OpenUI 5
[drupalday2017] - Decoupled frontend con Drupal 8 e OpenUI 5
 
[drupalday2017 - KEYNOTE] - Saving the world one Open Source project at a time
[drupalday2017 - KEYNOTE] - Saving the world one Open Source project at a time[drupalday2017 - KEYNOTE] - Saving the world one Open Source project at a time
[drupalday2017 - KEYNOTE] - Saving the world one Open Source project at a time
 
[drupalday2017] - Devel - D8 release party
[drupalday2017] - Devel - D8 release party[drupalday2017] - Devel - D8 release party
[drupalday2017] - Devel - D8 release party
 
[drupalday2017] - Async navigation with a lightweight ES6 framework
[drupalday2017] - Async navigation with a lightweight ES6 framework[drupalday2017] - Async navigation with a lightweight ES6 framework
[drupalday2017] - Async navigation with a lightweight ES6 framework
 
[drupalday2017] - Contenuti educativi digitali aperti, creare contenuti e dis...
[drupalday2017] - Contenuti educativi digitali aperti, creare contenuti e dis...[drupalday2017] - Contenuti educativi digitali aperti, creare contenuti e dis...
[drupalday2017] - Contenuti educativi digitali aperti, creare contenuti e dis...
 
[drupalday2017] - Venezia & Drupal. Venezia è Drupal!
[drupalday2017] - Venezia & Drupal. Venezia è Drupal![drupalday2017] - Venezia & Drupal. Venezia è Drupal!
[drupalday2017] - Venezia & Drupal. Venezia è Drupal!
 
[drupalday2017] - DevOps: strumenti di automazione per Drupal8
[drupalday2017] - DevOps: strumenti di automazione per Drupal8[drupalday2017] - DevOps: strumenti di automazione per Drupal8
[drupalday2017] - DevOps: strumenti di automazione per Drupal8
 
[drupalday2017] - Quando l’informazione è un servizio
[drupalday2017] - Quando l’informazione è un servizio[drupalday2017] - Quando l’informazione è un servizio
[drupalday2017] - Quando l’informazione è un servizio
 
[drupalday2017] - Cosa significa convertire un modulo da D7 a D8
[drupalday2017] - Cosa significa convertire un modulo da D7 a D8[drupalday2017] - Cosa significa convertire un modulo da D7 a D8
[drupalday2017] - Cosa significa convertire un modulo da D7 a D8
 
[drupalday2017] - DevOps: strumenti di automazione per Drupal8
[drupalday2017] - DevOps: strumenti di automazione per Drupal8[drupalday2017] - DevOps: strumenti di automazione per Drupal8
[drupalday2017] - DevOps: strumenti di automazione per Drupal8
 
Once you go cloud you never go down
Once you go cloud you never go downOnce you go cloud you never go down
Once you go cloud you never go down
 
Tooling per il tema in Drupal 8
Tooling per il tema in Drupal 8Tooling per il tema in Drupal 8
Tooling per il tema in Drupal 8
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 

Similaire à [drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager

Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)
Deepak Gupta
 
AWS CloudFormation Automation, TrafficScript, and Serverless architecture wit...
AWS CloudFormation Automation, TrafficScript, and Serverless architecture wit...AWS CloudFormation Automation, TrafficScript, and Serverless architecture wit...
AWS CloudFormation Automation, TrafficScript, and Serverless architecture wit...
PolarSeven Pty Ltd
 

Similaire à [drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager (20)

Fm 2
Fm 2Fm 2
Fm 2
 
5-WebServers.ppt
5-WebServers.ppt5-WebServers.ppt
5-WebServers.ppt
 
SignalR
SignalRSignalR
SignalR
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Unit 02: Web Technologies (2/2)
Unit 02: Web Technologies (2/2)Unit 02: Web Technologies (2/2)
Unit 02: Web Technologies (2/2)
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
 
Introduction to CloudStack API
Introduction to CloudStack APIIntroduction to CloudStack API
Introduction to CloudStack API
 
Architecting &Building Scalable Secure Web API
Architecting &Building Scalable Secure Web APIArchitecting &Building Scalable Secure Web API
Architecting &Building Scalable Secure Web API
 
Design Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyDesign Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John Hardy
 
Service management Dec 11
Service management Dec 11Service management Dec 11
Service management Dec 11
 
Service Management Dec 11
Service Management Dec 11Service Management Dec 11
Service Management Dec 11
 
Service Discovery using etcd, Consul and Kubernetes
Service Discovery using etcd, Consul and KubernetesService Discovery using etcd, Consul and Kubernetes
Service Discovery using etcd, Consul and Kubernetes
 
Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)
 
Driving containerd operations with gRPC
Driving containerd operations with gRPCDriving containerd operations with gRPC
Driving containerd operations with gRPC
 
5-WebServers.ppt
5-WebServers.ppt5-WebServers.ppt
5-WebServers.ppt
 
REST in Peace
REST in PeaceREST in Peace
REST in Peace
 
WCF - In a Week
WCF - In a WeekWCF - In a Week
WCF - In a Week
 
AAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
AAI-3218 Production Deployment Best Practices for WebSphere Liberty ProfileAAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
AAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
 
AWS CloudFormation Automation, TrafficScript, and Serverless architecture wit...
AWS CloudFormation Automation, TrafficScript, and Serverless architecture wit...AWS CloudFormation Automation, TrafficScript, and Serverless architecture wit...
AWS CloudFormation Automation, TrafficScript, and Serverless architecture wit...
 

Plus de DrupalDay

Plus de DrupalDay (8)

Da X a Drupal 8, migra tutto e vivi sereno
Da X a Drupal 8, migra tutto e vivi serenoDa X a Drupal 8, migra tutto e vivi sereno
Da X a Drupal 8, migra tutto e vivi sereno
 
Come progettare e realizzare una distribuzione in Drupal 8
Come progettare e realizzare una distribuzione in Drupal 8Come progettare e realizzare una distribuzione in Drupal 8
Come progettare e realizzare una distribuzione in Drupal 8
 
Drupal per la PA
Drupal per la PADrupal per la PA
Drupal per la PA
 
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case study
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case studyMantenere una distribuzione Drupal attraverso test coverage: Paddle case study
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case study
 
Invisiblefarm condivide l'esperienza DrupalGIS
Invisiblefarm condivide l'esperienza DrupalGISInvisiblefarm condivide l'esperienza DrupalGIS
Invisiblefarm condivide l'esperienza DrupalGIS
 
La semantica per automatizzare una redazione web: l'esperienza di Innolabplus.eu
La semantica per automatizzare una redazione web: l'esperienza di Innolabplus.euLa semantica per automatizzare una redazione web: l'esperienza di Innolabplus.eu
La semantica per automatizzare una redazione web: l'esperienza di Innolabplus.eu
 
"Twig e i belli dentro": panoramica sui nuovi standard di frontend-developmen...
"Twig e i belli dentro": panoramica sui nuovi standard di frontend-developmen..."Twig e i belli dentro": panoramica sui nuovi standard di frontend-developmen...
"Twig e i belli dentro": panoramica sui nuovi standard di frontend-developmen...
 
Drupal 8: dal download del Core alla pubblicazione in produzione. Cos'è cambi...
Drupal 8: dal download del Core alla pubblicazione in produzione. Cos'è cambi...Drupal 8: dal download del Core alla pubblicazione in produzione. Cos'è cambi...
Drupal 8: dal download del Core alla pubblicazione in produzione. Cos'è cambi...
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 

[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager

  • 3. http://www.bmeme.com Adriano Cori • drupal.org: aronne • github.com: Fatal-Error • twitter: @coriadriano • email: adriano.cori@bmeme.com return shuffle([ "programmazione", "famiglia", "videogames", "calcio", ]);
  • 4. HTTP DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: Adriano Cori, @bmeme DrupalDay Roma 3 Marzo 2017 CLIENT MANAGER
  • 5. HTTP CLIENT MANAGER “L'HyperText Transfer Protocol (HTTP) è un protocollo a livello applicativo usato come principale sistema per la trasmissione d'informazioni sul web ovvero in un'architettura tipica client- server.”- https://it.wikipedia.org/wiki/Hypertext_Transfer_Protocol DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST:
  • 6. HTTP REQUEST DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER • POST • GET • PUT, PATCH • DELETE • OPTIONS • HEAD • TRACE • CONNECT > Request Method • CREATE • RETRIEVE • UPDATE • DELETE > Request URI Lo uniform resource identifier indica l'oggetto della richiesta > Request Header • Host • User-Agent • Accept
  • 7. HTTP RESPONSE DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER • 200 • 301 • 302 • 307 • 400 • 404 • 500 • 505 > Response Status Ok Moved Permanently Found Temporary Redirect Bad Request Not Found Internal Server Error HTTP Version Unsupported > Response body Contiene il contenuto della risposta > Response Header • Date • Content-Type • Cache-Control
  • 8. DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER “REpresentational State Transfer (REST) è un tipo di architettura software per i sistemi di ipertesto distribuiti come il World Wide Web.”- https://it.wikipedia.org/wiki/Representational_State_Transfer “REST defines a set of architectural principles by which you can design Web services that focus on a system's resources, including how resource states are addressed and transferred over HTTP by a wide range of clients written in different languages.” - https://www.ibm.com/developerworks/webservices/library/ws-restful /**
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */ @see DrupalsparkfabrikPaoloPustorino::restInPieces()
  • 9. REST SERVICE DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER > HTTP Response HTTP/1.1 200 OK
 Content-Type: application/json; charset=UTF-8 
 [ { "id": 1, "title": "Ma che bella notizia", "body": "Lorem ipsum non passa mai di moda", "date": "2017-03-03 10:15:32” }, { "id": 2, "title": "Inizia il talk di @aronne", "body": "Lorem ipsum come se piovesse", "date": "2017-03-03 10:02:54” } ] GET /api/news?date=2017-03-03 HTTP/1.1 Host: example.com User-Agent: curl/7.43.0 Accept: application/json > HTTP Request
  • 10. DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER “An HTTP client uses HTTP to connect to a web server over the Internet to transfer documents or other data. The most well known types of HTTP Clients include web browsers.”- https://en.wikipedia.org/wiki/ Category:Hypertext_Transfer_Protocol_clients Cosa ci mette a disposizione Drupal 8? Drupal::httpClient() public static function httpClient() { return static::getContainer()->get('http_client'); } http_client:
 class: GuzzleHttpClient
 factory: http_client_factory:fromOptions
  • 11. DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER $news = Drupal::httpClient()->request(
 'GET',
 'http://api.example.com/news',
 ['date' => '2017-03-03']
 ); “Ahah..ma come Guzzle se fa dico io” Alternative?
  • 12. ALTERNATIVE DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER Creare una classe che faccia da wrapper al Drupal::httpClient() • Memorizzare l’host tanto per cominciare • Creare dei metodi ad hoc per ogni Request • Validazione dei parametri • Design pattern a piacere :) • Riusabilità del codice • … e poi un bel giorno….
  • 13. DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER
  • 14. REFACTORING DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER Creare una classe astratta che faccia da bla bla bla… • Programmazione orientata agli insulti • Il nuovo codice va ritestato • la tua ragazza ti lascia • il corvo si sbagliava riguardo alla pioggia • belle sbuffate • io manco ce volevo veni’ • e mettemocela n’altra if… • AggileGiggi me spiccia casa ma poi alla fine….
  • 15. DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER
  • 16. REFACTORING DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER Come si potrebbe migliorare ancora il nostro codice? • Rendendolo (se non lo si era già fatto) il più astratto possibile • Rimuovendo dal codice info relative agli endpoint, risorse e 
 parametri, spostandole invece su dei file di configurazione • cancellandolo…
  • 17. DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER
  • 18. DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER Http Client Manager introduces a new Guzzle based plugin which allows you to manage HTTP clients using Guzzle Service Descriptions via JSON files, in a simple and efficient way: "Service descriptions define web service APIs by documenting each operation, the operation's parameters, validation options for each parameter, an operation's response, how the response is parsed, and any errors that can be raised for an operation. Writing a service description for a web service allows you to more quickly consume a web service than writing concrete commands for each web service operation.” You will no longer need to write down Http services calls each times specifying endpoints and parameters in a totally decentralized way.
  • 19. DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER > Http Services Api definition via *.http_services_api.yml file example_services: title: "Example Services - posts API" api_path: "src/api/example_services.json" base_url: "http://api.example.com" auth_services: title: "Another Example Services - auth API" api_path: "src/api/auth_services.json" base_url: “http://auth.services.com" > Overridable Services Api definition via settings.php file $settings['http_services_api']['example_services'] = [ 'title' => 'Example Services - posts API (Development)', 'base_url' => 'http://api.example.dev', ]; > Ad Hoc client definition via *.services.yml file services: example_api.http_client: parent: http_client_manager.client_base arguments: ['example_services']
  • 20. DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER > src/api/example_services.json { "name": "ExampleServicesApi", "apiVersion": "2016-07-29", "description": "Example Services API descriptions.", "includes" : [ "resources/posts.json" ] } > src/api/resources/posts.json { "operations": { "FindPosts": { "httpMethod": "GET", "uri": "posts/{postId}", "summary": "Find posts", "parameters": { "postId": { "location": "uri", "description": "Filter posts by id", "required": false, "type": "string" } } }, "models": {} } HTTP SERVICE DESCRIPTIONS
  • 21. DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER > Multiple ways to instantiate http clients // Client instantiation via http_client_manager service factory method. $client = Drupal::service('http_client_manager.factory')->get('example_services'); // Client instantiation via service. $client = Drupal::service(‘example_api.http_client'); > Multiple ways to execute http requests // Call method usage. $latestPosts = $client->call('FindPosts', ['limit' => '10', 'sort' => 'desc']); // Magic method usage. $latestPosts = $client->findPosts(['limit' => '10', 'sort' => 'desc']);
  • 22. DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER You can also create and store (bookmark) predefined requests via web UI as Configuration Entities (exportable via Configuration Manager), and execute them from your code in this way: // Http Config Request usage via Config Entity static method. $latestPosts = HttpConfigRequest::load('find_posts')->execute(); // Http Config Request usage via entity type manager. $latestPosts = $this->entityTypeManager() ->getStorage('http_config_request') ->load('find_posts') ->execute();
  • 23. DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER /** * Class HttpEventSubscriber. */ class HttpEventSubscriber implements EventSubscriberInterface { /** * {@inheritdoc} */ static function getSubscribedEvents() { return [ 'request.before_send' => array('onRequestBeforeSend', -1000) ]; } /** * Request before-send event handler * * @param Event $event * Event received */ public function onRequestBeforeSend(Event $event) { // your code goes here… } }
  • 24. CONCLUSIONI DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: HTTP CLIENT MANAGER HTTP Client Manager in cosa ci aiuta? • Ad evitare la dispersione del codice centralizzandone l’utilizzo • Ad evitare di scrivere altro codice in favore di un riutilizzo delle 
 descrizioni dei servizi • A risolvere un problema comune proponendosi quindi come un
 nuovo standard per la gestione delle sorgenti e per la
 presentazione di dati nelle istanze Drupal che consumano servizi
  • 25. HTTP CLIENT MANAGER DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: LIVE DEMO QUESTIONS & ANSWERS
  • 26. HTTP CLIENT MANAGER DRUPAL COME FRONT-END CHE CONSUMA SERVIZI REST: LIVE DEMO QUESTIONS & ANSWERS