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)

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

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)

PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Approach and Philosophy of On baking technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Advanced IT Governance
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
KodekX | Application Modernization Development
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Electronic commerce courselecture one. Pdf
NewMind AI Monthly Chronicles - July 2025
Per capita expenditure prediction using model stacking based on satellite ima...
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Diabetes mellitus diagnosis method based random forest with bat algorithm
Approach and Philosophy of On baking technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Understanding_Digital_Forensics_Presentation.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Advanced IT Governance
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
KodekX | Application Modernization Development
GamePlan Trading System Review: Professional Trader's Honest Take
Electronic commerce courselecture one. Pdf

[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