SlideShare a Scribd company logo
Services +
REST and OAuth
The purpose of services
Create a Drupal API for exposing web API:s
The official version
- Create a unified Drupal API for web
services to be exposed in a variety of
different server formats.

- Provide a service browser to be able to
test methods.

- Allow distribution of API keys for developer
access.
Services
Functionality split into three kinds of
modules that provides:

✦   Servers
✦   Services
✦   Authentication mechanisms (new in 2.x)
Servers
✦   REST
✦   XMLRPC
✦   JSONRPC
✦   SOAP
✦   AMF (Binary Flash RPC protocol)
Services
✦       That exposes core
    ✦    Node, user, taxonomy, menu, file,
✦       That exposes other modules
    ✦    Views
✦       And additional services implemented in other
        contrib modules that I cant remember right
        now.
Authentication
✦   OAuth
✦   Key authentication
Implementing services
✦   Either as methods
✦   ...or (since version 2.x) as resources
Methods
✦   Pretty similar to the menu system
✦   Each service-implementing module returns a
    non-associative array with methods
✦   Method definitions contains a method
    attribute: “node.get”, “node.view”,
    “node.save”, “node.delete”
✦   ...and information about callbacks,
    parameters, access rules et cetera.
<?php
/**
 * Implementation of hook_service().
 */
function node_service_service
          node_service_service() {
  return array
          array(
    // node.get
    array
    array(
      '#method'           => 'node.get',
      '#callback'         => 'node_service_get',
      '#access callback' => 'node_service_get_access',
      '#file'             => array
                             array('file' => 'inc', 'module' => 'node_service'),
      '#args'             => array
                             array(
        array
        array(
          '#name'           => 'nid',
          '#type'           => 'int',
          '#description'    => t('A node ID.')),
        ...
      '#return'           => 'struct',
      '#help'             => t('Returns a node data.')
    ),
Drawbacks
✦       No semantics
    ✦    node.view is treated exactly like node.delete
✦       Lack of consistency
    ✦    “taxonomy.saveTerm”, “node.save”
    ✦    “node.view”, “user.get”
✦       Lack of structure makes it hard to alter through
        alter hooks.
Resources
✦       Adds semantics to the methods
✦       Natural grouping around resources
    ✦    no more “taxonomy.saveTerm”
✦       Methods are divided into CRUD-operations,
        actions, targeted actions and relationships
Structure - CRUD
✦       Resource
    ✦   Create
    ✦   Retrieve
    ✦   Update
    ✦   Delete
    ✦   (Index)
Extensions of CRUD
✦       Actions
    ✦    Similar to static class methods:
         Node::publish_my_drafts()
✦       Targeted actions
    ✦    Like class methods: $node->publish()
✦       Relationships
    ✦    Like targeted actions but for read-operations:
         $node->get_comments()
All old services can be expressed
as resources
✦   Direct translation through adding the old
    methods (taxonomy.saveTerm,
    saveVocabulary, getTree, selectNodes) as
    actions on the taxonomy resource.
✦   Or even better, create them as real
    resources (vocabulary and term).
OAuth
✦       Secure protocol for avoiding “the
        password anti-pattern”.
✦       A strong emerging standard.
✦       Client implementations available
        for most small and large
        languages.
    ✦    See http://oauth.net/code
OAuth workflow for the user
✦   Initiates the authorization process in a
    third-party application (consumer). Is
    redirected to our site (the provider).
✦   The user logs in to the provider and is asked
    to authorize the consumer.
✦   The user is sent back to the consumer. And
    were done!
Token-based security
✦       Three tokens (key+secret) are involved: consumer-
        token, request-token and access-token.
    ✦    The consumer uses it’s consumer-token to retrieve a
         request token.
    ✦    The user authorizes our request token.
    ✦    The consumer uses it’s request token to fetch a
         access token.
    ✦    The consumer can then use the consumer+access-
         token to access protected resources.
The REST server
✦       REST is designed to work as well as possible with HTTP.
✦       All resources are accesible though a url
    ✦       Create: POST http://example.com/node
    ✦       Retrieve: GET http://example.com/node/123
        ✦    Index: GET http://example.com/node
    ✦       Update: PUT http://example.com/node/123
    ✦       Delete: DELETE http://example.com/node/123
The extensions to CRUD
✦       Actions
    ✦    POST
         http://example.com/node/publish_my_drafts
✦       Targeted actions
    ✦    POST
         http://example.com/node/123/publish
✦       Relationships
    ✦    GET
         http://example.com/node/123/comments
Multiple response formats
✦       XMLRPC always returns XML, JSONRPC returns JSON, SOAP
        returns XML+cruft and so on.
✦       REST is format agnostic and can give responses in different
        formats based on file endings and Accept-headers.
    ✦    GET http://example.com/node/123.json
    ✦    GET http://example.com/node/123.xml
    ✦    GET http://example.com/node/123.php
✦       Other modules can add and alter response formats through
        hook_rest_server_response_formatters_alter().
All response formats inherit from
RESTServerView
      <?php

     /**
      * Base class for all response format views
      */
     abstract class RESTServerView {
       protected $model;
       protected $arguments;

         function __construct
                   __construct($model, $arguments= array
                                                 = array()) {
           $this->
                ->model = $model;
           $this->
                ->arguments = $arguments;
         }

         public abstract function render
                                  render();
     }
More advanced response formats
✦       The response formats that can’t use simple
        serialization
    ✦    RSS, iCal, xCal med flera
✦       The format can then demand that the
        method shall implement a data model that
        works like a adapter.
'XCalFormatView' => array
                               array(
             'file' => 'XCalFormatView.inc',
          ),
Example from xCal
 }
     );


 function xcal_..._formatters_alter &$formatters) {
            xcal_..._formatters_alter(&
   $formatters['xcal'] = array
                          array(
      'model' => 'ResourceTimeFeedModel',
      'mime types' => array
                      array('application/xcal+xml'),
      'view' => 'XCalFormatView',
   );
   $formatters['ical'] = array
                          array(
      'model' => 'ResourceTimeFeedModel',
      'mime types' => array
                      array('text/calendar'),
      'view' => 'XCalFormatView',
      'view arguments' => array
                          array('transform'=>
                                           =>'ical'),
   );
 }
The resource declares support for
     ),
the model, not the format
   ),
   'models' => array
                 array(
      'ResourceFeedModel' => array
                              array(
         'class' => 'NodeResourceFeedModel',
      ),
      'ResourceTimeFeedModel' => array
                                  array(
         'class' => 'NodeResourceFeedModel',
      ),
   ),
   'access arguments' => array
                           array('access content'),
Multiple input-formats
✦       Built in support for x-www-form-urlencoded, yaml, json and
        serialized php.
✦       Can be extended through
        hook_rest_server_request_parsers_alter().
✦       Determined by the Content-type-header for the call and
        therefore matched to mime-types:
    ✦    'application/json' => 'RESTServer::parseJSON',
    ✦    'application/vnd.php.serialized' => 'RESTServer::parsePHP',
My view on the future of services -
3.x
✦       The old RPC-oriented methods are
        completely removed and are replaced by
        resources.
    ✦    Possibly support translation of method
         declarations to a resource with actions.
✦       Endpoints: modules and administrators will
        be able to publish and configure servers on
        arbitrary locations in the menu system.
Why endpoints?
Today all installed services are
always available on all installed
servers and they all have to use
the same auth method.
Why Endpoints?
✦       Today it’s not possible for modules to use services
        to expose an API.
    ✦    API = services + server + authentication
         mechanism
✦       Or rather - only one API can be exposed at a time
✦       This becomes a problem if services is going to be
        used as a framework for other modules to publish
        API:s
Endpoints
✦       Can be configured independently of each other.
        And you can choose:
    ✦    which server that should be used, and what
         path its should be placed on
    ✦    exactly what services should be exposed
    ✦    what authentication module that should be
         used, and how it should be configured
Endpoints makes it possible to
✦   Expose several different API:s on one Drupal
    install
✦   Define an API in your module that will
    become available when the module is
    installed.
✦   Package your API as a feature, this is
    planned to be supported through chaos
    tools.
Example of
a endpoint-
declaration
/**
 * Implementation of hook_services_endpoints().
 */
function conglomerate_services_endpoints
           conglomerate_services_endpoints() {
  return array
           array(
    'conglomerate' => array
                       array(
      'title' => 'Conglomerate API',
      'server' => 'rest_server',
      'path' => 'api',
      'authentication' => 'services_oauth',
      'authentication_settings' => array
                                    array(
         'oauth_context' => 'conglomerate',
      ),
      'resources' => array
                      array(
         'conglomerate-content' => array
                                   array(
           'alias' => 'content',
           'operations' => array
                           array(
             'create' => array
                         array(
               'enabled' => TRUE,
               'oauth_credentials' => 'token',
               'oauth_authorization' => '*',
             ),
             'retrieve' => array
                           array(
               'enabled' => TRUE,
               'oauth_credentials' => 'unsigned_consumer',
               'oauth_authorization' => 'read',
             ),
             'update' => array
                         array(
OAuth and Endpoints
✦       OAuth now has support for contexts.
    ✦    Consumers are always placed in a context
    ✦    Authentications are therefore only valid
         within this context.
    ✦    Each context has it’s own authorization levels
✦       Endpoints in services can either use separate
        contexts or share contexts.
OAuth context declaration in code
<?php

/**
  * Implementation of hook_oauth_default_contexts().
  */
function conglomerate_oauth_default_contexts
            conglomerate_oauth_default_contexts() {
   return array
            array(
      'conglomerate' => array
                         array(
        '*' => array
               array(
          'title' => 'Yes, I want to connect !appname to !sitename',
          'description' => 'This will allow your site !appname to push content to !sitename',
          'weight' => - 1,
        ),
        'read' => array
                  array(
          'title' => 'I want to connect, but just to get stuff from !sitename',
          'description' => 'This will allow !appname to fetch content from !sitename, but it will not
allow any information to be pushed to !sitename.',
          'weight' => 0,
        ),
      )
   );
}

/**
Hugo Wetterberg
            @hugowett
         hugo@goodold.se
http://github.com/hugowetterberg

More Related Content

What's hot

Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Fabien Potencier
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Nate Abele
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Fabien Potencier
 
Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Fabien Potencier
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201Fabien Potencier
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
Pavel Makhrinsky
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010Fabien Potencier
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
Hugo Hamon
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
Nate Abele
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti
 
Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3
Fabien Potencier
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2Hugo Hamon
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
Leonardo Proietti
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
Rafael Dohms
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
Hugo Hamon
 

What's hot (20)

Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
 
Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3Dependency Injection with PHP 5.3
Dependency Injection with PHP 5.3
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
 

Viewers also liked

S.Olson Portfolio
S.Olson PortfolioS.Olson Portfolio
S.Olson Portfolio
olsonst
 
Ketensamenwerking: een voorwaarde voor succes
Ketensamenwerking: een voorwaarde voor succesKetensamenwerking: een voorwaarde voor succes
Ketensamenwerking: een voorwaarde voor succes
Paviljoen 2030
 
Duurzaamheid in de praktijk
Duurzaamheid in de praktijkDuurzaamheid in de praktijk
Duurzaamheid in de praktijk
Paviljoen 2030
 
Early Florida2
Early Florida2Early Florida2
Early Florida2JohnPotter
 
Workshop Sundbybergskommun 20100307
Workshop Sundbybergskommun 20100307Workshop Sundbybergskommun 20100307
Workshop Sundbybergskommun 20100307
One Hot Pixel
 
Vegetarian lasagne
Vegetarian lasagneVegetarian lasagne
Vegetarian lasagneMonica777
 
Adopteer een Wijk
Adopteer een WijkAdopteer een Wijk
Adopteer een Wijk
Paviljoen 2030
 
Maak kennis met paviljoen2030
Maak kennis met paviljoen2030Maak kennis met paviljoen2030
Maak kennis met paviljoen2030Paviljoen 2030
 
Accelerated Trainers Workshop For Trainers Short
Accelerated Trainers Workshop For Trainers   ShortAccelerated Trainers Workshop For Trainers   Short
Accelerated Trainers Workshop For Trainers Short
krysgadd
 
Redfox Powerpoint
Redfox PowerpointRedfox Powerpoint
Redfox Powerpointhannahluton
 
Our Common Future 2.0 - roadmaps for our future society
Our Common Future 2.0 - roadmaps for our future societyOur Common Future 2.0 - roadmaps for our future society
Our Common Future 2.0 - roadmaps for our future society
Paviljoen 2030
 
Hernia Tapp
Hernia TappHernia Tapp
Hernia TappBPTE
 

Viewers also liked (17)

S.Olson Portfolio
S.Olson PortfolioS.Olson Portfolio
S.Olson Portfolio
 
Ketensamenwerking: een voorwaarde voor succes
Ketensamenwerking: een voorwaarde voor succesKetensamenwerking: een voorwaarde voor succes
Ketensamenwerking: een voorwaarde voor succes
 
Duurzaamheid in de praktijk
Duurzaamheid in de praktijkDuurzaamheid in de praktijk
Duurzaamheid in de praktijk
 
Early Florida2
Early Florida2Early Florida2
Early Florida2
 
Workshop Sundbybergskommun 20100307
Workshop Sundbybergskommun 20100307Workshop Sundbybergskommun 20100307
Workshop Sundbybergskommun 20100307
 
Vegetarian lasagne
Vegetarian lasagneVegetarian lasagne
Vegetarian lasagne
 
Pagerank
PagerankPagerank
Pagerank
 
Ejercicio Curso
Ejercicio CursoEjercicio Curso
Ejercicio Curso
 
Adopteer een Wijk
Adopteer een WijkAdopteer een Wijk
Adopteer een Wijk
 
Pagerank
PagerankPagerank
Pagerank
 
Maak kennis met paviljoen2030
Maak kennis met paviljoen2030Maak kennis met paviljoen2030
Maak kennis met paviljoen2030
 
Accelerated Trainers Workshop For Trainers Short
Accelerated Trainers Workshop For Trainers   ShortAccelerated Trainers Workshop For Trainers   Short
Accelerated Trainers Workshop For Trainers Short
 
Why Mitel
Why MitelWhy Mitel
Why Mitel
 
Redfox Powerpoint
Redfox PowerpointRedfox Powerpoint
Redfox Powerpoint
 
Reg
RegReg
Reg
 
Our Common Future 2.0 - roadmaps for our future society
Our Common Future 2.0 - roadmaps for our future societyOur Common Future 2.0 - roadmaps for our future society
Our Common Future 2.0 - roadmaps for our future society
 
Hernia Tapp
Hernia TappHernia Tapp
Hernia Tapp
 

Similar to Services Drupalcamp Stockholm 2009

Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
Shinya Ohyanagi
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
Jonathan Wage
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)
tompunk
 
Web internship Yii Framework
Web internship  Yii FrameworkWeb internship  Yii Framework
Web internship Yii Framework
Noveo
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
Jason Ragsdale
 
Built-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsBuilt-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIs
Ulf Wendel
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
Wei Ru
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
Lukas Smith
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
Valentine Matsveiko
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
LEDC 2016
 
Data models in Angular 1 & 2
Data models in Angular 1 & 2Data models in Angular 1 & 2
Data models in Angular 1 & 2
Adam Klein
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
Michelangelo van Dam
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
SC5.io
 
Resource Routing in ExpressionEngine
Resource Routing in ExpressionEngineResource Routing in ExpressionEngine
Resource Routing in ExpressionEngine
MichaelRog
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
Marcus Ramberg
 
Opencast Admin UI - Introduction to developing using AngularJS
Opencast Admin UI - Introduction to developing using AngularJSOpencast Admin UI - Introduction to developing using AngularJS
Opencast Admin UI - Introduction to developing using AngularJS
buttyx
 
AngularJS.part1
AngularJS.part1AngularJS.part1
AngularJS.part1
Andrey Kolodnitsky
 

Similar to Services Drupalcamp Stockholm 2009 (20)

Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
RESTful web services
RESTful web servicesRESTful web services
RESTful web services
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)
 
Web internship Yii Framework
Web internship  Yii FrameworkWeb internship  Yii Framework
Web internship Yii Framework
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
 
Built-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsBuilt-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIs
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Data models in Angular 1 & 2
Data models in Angular 1 & 2Data models in Angular 1 & 2
Data models in Angular 1 & 2
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
Resource Routing in ExpressionEngine
Resource Routing in ExpressionEngineResource Routing in ExpressionEngine
Resource Routing in ExpressionEngine
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Opencast Admin UI - Introduction to developing using AngularJS
Opencast Admin UI - Introduction to developing using AngularJSOpencast Admin UI - Introduction to developing using AngularJS
Opencast Admin UI - Introduction to developing using AngularJS
 
AngularJS.part1
AngularJS.part1AngularJS.part1
AngularJS.part1
 

Recently uploaded

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 

Services Drupalcamp Stockholm 2009

  • 1.
  • 3. The purpose of services Create a Drupal API for exposing web API:s
  • 4. The official version - Create a unified Drupal API for web services to be exposed in a variety of different server formats. - Provide a service browser to be able to test methods. - Allow distribution of API keys for developer access.
  • 5. Services Functionality split into three kinds of modules that provides: ✦ Servers ✦ Services ✦ Authentication mechanisms (new in 2.x)
  • 6. Servers ✦ REST ✦ XMLRPC ✦ JSONRPC ✦ SOAP ✦ AMF (Binary Flash RPC protocol)
  • 7. Services ✦ That exposes core ✦ Node, user, taxonomy, menu, file, ✦ That exposes other modules ✦ Views ✦ And additional services implemented in other contrib modules that I cant remember right now.
  • 8. Authentication ✦ OAuth ✦ Key authentication
  • 9. Implementing services ✦ Either as methods ✦ ...or (since version 2.x) as resources
  • 10. Methods ✦ Pretty similar to the menu system ✦ Each service-implementing module returns a non-associative array with methods ✦ Method definitions contains a method attribute: “node.get”, “node.view”, “node.save”, “node.delete” ✦ ...and information about callbacks, parameters, access rules et cetera.
  • 11. <?php /** * Implementation of hook_service(). */ function node_service_service node_service_service() { return array array( // node.get array array( '#method' => 'node.get', '#callback' => 'node_service_get', '#access callback' => 'node_service_get_access', '#file' => array array('file' => 'inc', 'module' => 'node_service'), '#args' => array array( array array( '#name' => 'nid', '#type' => 'int', '#description' => t('A node ID.')), ... '#return' => 'struct', '#help' => t('Returns a node data.') ),
  • 12. Drawbacks ✦ No semantics ✦ node.view is treated exactly like node.delete ✦ Lack of consistency ✦ “taxonomy.saveTerm”, “node.save” ✦ “node.view”, “user.get” ✦ Lack of structure makes it hard to alter through alter hooks.
  • 13. Resources ✦ Adds semantics to the methods ✦ Natural grouping around resources ✦ no more “taxonomy.saveTerm” ✦ Methods are divided into CRUD-operations, actions, targeted actions and relationships
  • 14. Structure - CRUD ✦ Resource ✦ Create ✦ Retrieve ✦ Update ✦ Delete ✦ (Index)
  • 15. Extensions of CRUD ✦ Actions ✦ Similar to static class methods: Node::publish_my_drafts() ✦ Targeted actions ✦ Like class methods: $node->publish() ✦ Relationships ✦ Like targeted actions but for read-operations: $node->get_comments()
  • 16. All old services can be expressed as resources ✦ Direct translation through adding the old methods (taxonomy.saveTerm, saveVocabulary, getTree, selectNodes) as actions on the taxonomy resource. ✦ Or even better, create them as real resources (vocabulary and term).
  • 17. OAuth ✦ Secure protocol for avoiding “the password anti-pattern”. ✦ A strong emerging standard. ✦ Client implementations available for most small and large languages. ✦ See http://oauth.net/code
  • 18. OAuth workflow for the user ✦ Initiates the authorization process in a third-party application (consumer). Is redirected to our site (the provider). ✦ The user logs in to the provider and is asked to authorize the consumer. ✦ The user is sent back to the consumer. And were done!
  • 19. Token-based security ✦ Three tokens (key+secret) are involved: consumer- token, request-token and access-token. ✦ The consumer uses it’s consumer-token to retrieve a request token. ✦ The user authorizes our request token. ✦ The consumer uses it’s request token to fetch a access token. ✦ The consumer can then use the consumer+access- token to access protected resources.
  • 20. The REST server ✦ REST is designed to work as well as possible with HTTP. ✦ All resources are accesible though a url ✦ Create: POST http://example.com/node ✦ Retrieve: GET http://example.com/node/123 ✦ Index: GET http://example.com/node ✦ Update: PUT http://example.com/node/123 ✦ Delete: DELETE http://example.com/node/123
  • 21. The extensions to CRUD ✦ Actions ✦ POST http://example.com/node/publish_my_drafts ✦ Targeted actions ✦ POST http://example.com/node/123/publish ✦ Relationships ✦ GET http://example.com/node/123/comments
  • 22. Multiple response formats ✦ XMLRPC always returns XML, JSONRPC returns JSON, SOAP returns XML+cruft and so on. ✦ REST is format agnostic and can give responses in different formats based on file endings and Accept-headers. ✦ GET http://example.com/node/123.json ✦ GET http://example.com/node/123.xml ✦ GET http://example.com/node/123.php ✦ Other modules can add and alter response formats through hook_rest_server_response_formatters_alter().
  • 23. All response formats inherit from RESTServerView <?php /** * Base class for all response format views */ abstract class RESTServerView { protected $model; protected $arguments; function __construct __construct($model, $arguments= array = array()) { $this-> ->model = $model; $this-> ->arguments = $arguments; } public abstract function render render(); }
  • 24. More advanced response formats ✦ The response formats that can’t use simple serialization ✦ RSS, iCal, xCal med flera ✦ The format can then demand that the method shall implement a data model that works like a adapter.
  • 25. 'XCalFormatView' => array array( 'file' => 'XCalFormatView.inc', ), Example from xCal } ); function xcal_..._formatters_alter &$formatters) { xcal_..._formatters_alter(& $formatters['xcal'] = array array( 'model' => 'ResourceTimeFeedModel', 'mime types' => array array('application/xcal+xml'), 'view' => 'XCalFormatView', ); $formatters['ical'] = array array( 'model' => 'ResourceTimeFeedModel', 'mime types' => array array('text/calendar'), 'view' => 'XCalFormatView', 'view arguments' => array array('transform'=> =>'ical'), ); }
  • 26. The resource declares support for ), the model, not the format ), 'models' => array array( 'ResourceFeedModel' => array array( 'class' => 'NodeResourceFeedModel', ), 'ResourceTimeFeedModel' => array array( 'class' => 'NodeResourceFeedModel', ), ), 'access arguments' => array array('access content'),
  • 27. Multiple input-formats ✦ Built in support for x-www-form-urlencoded, yaml, json and serialized php. ✦ Can be extended through hook_rest_server_request_parsers_alter(). ✦ Determined by the Content-type-header for the call and therefore matched to mime-types: ✦ 'application/json' => 'RESTServer::parseJSON', ✦ 'application/vnd.php.serialized' => 'RESTServer::parsePHP',
  • 28. My view on the future of services - 3.x ✦ The old RPC-oriented methods are completely removed and are replaced by resources. ✦ Possibly support translation of method declarations to a resource with actions. ✦ Endpoints: modules and administrators will be able to publish and configure servers on arbitrary locations in the menu system.
  • 29. Why endpoints? Today all installed services are always available on all installed servers and they all have to use the same auth method.
  • 30. Why Endpoints? ✦ Today it’s not possible for modules to use services to expose an API. ✦ API = services + server + authentication mechanism ✦ Or rather - only one API can be exposed at a time ✦ This becomes a problem if services is going to be used as a framework for other modules to publish API:s
  • 31. Endpoints ✦ Can be configured independently of each other. And you can choose: ✦ which server that should be used, and what path its should be placed on ✦ exactly what services should be exposed ✦ what authentication module that should be used, and how it should be configured
  • 32. Endpoints makes it possible to ✦ Expose several different API:s on one Drupal install ✦ Define an API in your module that will become available when the module is installed. ✦ Package your API as a feature, this is planned to be supported through chaos tools.
  • 34. /** * Implementation of hook_services_endpoints(). */ function conglomerate_services_endpoints conglomerate_services_endpoints() { return array array( 'conglomerate' => array array( 'title' => 'Conglomerate API', 'server' => 'rest_server', 'path' => 'api', 'authentication' => 'services_oauth', 'authentication_settings' => array array( 'oauth_context' => 'conglomerate', ), 'resources' => array array( 'conglomerate-content' => array array( 'alias' => 'content', 'operations' => array array( 'create' => array array( 'enabled' => TRUE, 'oauth_credentials' => 'token', 'oauth_authorization' => '*', ), 'retrieve' => array array( 'enabled' => TRUE, 'oauth_credentials' => 'unsigned_consumer', 'oauth_authorization' => 'read', ), 'update' => array array(
  • 35. OAuth and Endpoints ✦ OAuth now has support for contexts. ✦ Consumers are always placed in a context ✦ Authentications are therefore only valid within this context. ✦ Each context has it’s own authorization levels ✦ Endpoints in services can either use separate contexts or share contexts.
  • 36. OAuth context declaration in code <?php /** * Implementation of hook_oauth_default_contexts(). */ function conglomerate_oauth_default_contexts conglomerate_oauth_default_contexts() { return array array( 'conglomerate' => array array( '*' => array array( 'title' => 'Yes, I want to connect !appname to !sitename', 'description' => 'This will allow your site !appname to push content to !sitename', 'weight' => - 1, ), 'read' => array array( 'title' => 'I want to connect, but just to get stuff from !sitename', 'description' => 'This will allow !appname to fetch content from !sitename, but it will not allow any information to be pushed to !sitename.', 'weight' => 0, ), ) ); } /**
  • 37. Hugo Wetterberg @hugowett hugo@goodold.se http://github.com/hugowetterberg