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

More Related Content

PDF
[drupalday2017] - Speed-up your Drupal instance!
PDF
[drupalday2017] - REST in pieces
PDF
Apache Sling as an OSGi-powered REST middleware
PDF
DevOps tools for everyone - Vagrant, Puppet and Webmin
PDF
Tech Webinar: Offline First: Creare un'app Phonegap che funzioni offline e si...
PPT
Build Your Own CMS with Apache Sling
ODP
Single Page Applications in Drupal
PDF
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
[drupalday2017] - Speed-up your Drupal instance!
[drupalday2017] - REST in pieces
Apache Sling as an OSGi-powered REST middleware
DevOps tools for everyone - Vagrant, Puppet and Webmin
Tech Webinar: Offline First: Creare un'app Phonegap che funzioni offline e si...
Build Your Own CMS with Apache Sling
Single Page Applications in Drupal
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools

What's hot (20)

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

Viewers also liked (20)

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

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

PDF
Build a Restfull app using drupal
PDF
Drupal8 for Symfony Developers (PHP Day Verona 2017)
PDF
Services in Drupal 8
PDF
RESTful Web Services in Drupal7
PPTX
Drupal 7 Web Services Crash Course
PDF
Drupal8 for Symfony developers - Dutch PHP
PPT
Drupal As A RESTful Backend For Client Side Applications
PDF
Guzzle in Drupal 8 and as a REST client - Артем Мирошник
PDF
[Srijan Wednesday Webinar] Decoupled Demystified: The Present & Future of Dr...
PDF
Web Services Tutorial
PDF
Drupal South 2015: Introduction to Web Services. Services in Drupal 8.
PDF
Web services tutorial
PDF
Using HttpKernelInterface for Painless Integration
PDF
Talking to Web Services
PDF
Learn Drupal 8 Render Pipeline
PDF
Ruby HTTP clients comparison
ODP
что нового в мире Services
PDF
Android Performance #4: Network
PDF
Drupal 8 simple page: Mi primer proyecto en Drupal 8.
PDF
REST APIS web development for backend familiarity
Build a Restfull app using drupal
Drupal8 for Symfony Developers (PHP Day Verona 2017)
Services in Drupal 8
RESTful Web Services in Drupal7
Drupal 7 Web Services Crash Course
Drupal8 for Symfony developers - Dutch PHP
Drupal As A RESTful Backend For Client Side Applications
Guzzle in Drupal 8 and as a REST client - Артем Мирошник
[Srijan Wednesday Webinar] Decoupled Demystified: The Present & Future of Dr...
Web Services Tutorial
Drupal South 2015: Introduction to Web Services. Services in Drupal 8.
Web services tutorial
Using HttpKernelInterface for Painless Integration
Talking to Web Services
Learn Drupal 8 Render Pipeline
Ruby HTTP clients comparison
что нового в мире Services
Android Performance #4: Network
Drupal 8 simple page: Mi primer proyecto en Drupal 8.
REST APIS web development for backend familiarity

More from DrupalDay (8)

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

Recently uploaded (20)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Electronic commerce courselecture one. Pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Spectroscopy.pptx food analysis technology
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
KodekX | Application Modernization Development
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
“AI and Expert System Decision Support & Business Intelligence Systems”
Transforming Manufacturing operations through Intelligent Integrations
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
MYSQL Presentation for SQL database connectivity
Electronic commerce courselecture one. Pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
GamePlan Trading System Review: Professional Trader's Honest Take
Understanding_Digital_Forensics_Presentation.pptx
Chapter 3 Spatial Domain Image Processing.pdf
Machine learning based COVID-19 study performance prediction
Review of recent advances in non-invasive hemoglobin estimation
Advanced methodologies resolving dimensionality complications for autism neur...
Spectroscopy.pptx food analysis technology
The AUB Centre for AI in Media Proposal.docx
Per capita expenditure prediction using model stacking based on satellite ima...
madgavkar20181017ppt McKinsey Presentation.pdf
cuic standard and advanced reporting.pdf
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
KodekX | Application Modernization Development
Dropbox Q2 2025 Financial Results & Investor Presentation

[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: [email protected] 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