Skip to content

Latest commit

 

History

History
237 lines (187 loc) · 8.69 KB

2.9-web-services.md

File metadata and controls

237 lines (187 loc) · 8.69 KB

Web Services

From RESTful Web Services API overview:

The RESTful Web Services API is new in Drupal 8. Expose entities as REST resources either to build a decoupled Drupal site, to let a native mobile iOS/Android app talk consume/feed a Drupal site, or to integrate with some web service.

Modules

The following Web Services modules are available in core:

REST Request Fundamentals

Safe HTTP Methods (read-only):

  • GET - Request data from a URI
  • HEAD - Retrieve headers from a URI
  • OPTIONS - Request available communication options
  • TRACE - Echoes back request sent to server

Unsafe HTTP Methods (write)

  • CONNECT - Opens a raw connection to a host through a proxy chain
  • DELETE - Requests that a server delete the resource at URI
  • PATCH - Request changes on a URI
  • POST - Submit data to a URI
  • PUT - Request submitted data be stored under a URI (currently not supported)

All unsafe methods require X-CSRF-Token request header, which can be retrieved at /rest/session/token.

Serialization Formats

From RESTful Web Services API overview:

  1. Always specify the ?_format query argument, e.g. http://example.com/node/1?_format=json
  2. When sending a request body containing data in that format, specify the Content-Type request header. This is the case for POST and PATCH.

Authentication

From RESTful Web Services API overview:

  • basic - The quickest way to get started is to use basic HTTP Authentication. Enable the Basic Auth module found in core, then send your drupal username and password using HTTP Authorization Headers
  • cookie - Use the cookie granted to an authenticated user.

You can also use third-party modules to provide support for other authentication such as OAuth.

REST Configuration

Note: These instructions are for Drupal 8.2 and later. See RESTful Web Services API overview for information on configuring Drupal 8.0 & 8.1.

Configuration Methods

Configurations are managed with YAML but can setup via REST UI module.

From RESTful Web Services API overview:

Each REST resource has a \Drupal\rest\RestResourceConfigInterface config entity that corresponds to a @RestResource plugin. Without such a config entity, the REST resource plugin will not be available for use.

There are two methods for configuring resources:

  • granularity: method: Set serialization formats and authentication per HTTP method.
  • granularity: resource: Set serialization formats and authentication per resource.

Examples:

...
granularity: method
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - basic_auth
      - cookie
...
...
granularity: resource
configuration:
  methods:
    - GET
    ...
  formats:
    - json
    ...
  authentication:
    - basic_auth
...

Examples

Using lessons learned in 2.7 - Configuration Management, import the following configuration, specifying REST resource configuration as the configuration type:

id: entity.node
plugin_id: 'entity:node'
granularity: resource
configuration:
  methods:
    - GET
    - POST
    - PATCH
    - DELETE
  formats:
    - json
    - hal_json
    - xml
  authentication:
    - basic_auth
    - cookie

The above configuration supports GET/POST/PATCH/DELETE requests.

Since this creates a generic endpoint, this data can now be consumed by any number of languages, frameworks and applications. The following examples illustrate a few different options:

GET

Assuming you have a node previously setup with nid of 1, you can test this by navigating to /node/1?_format=json in your browser. If setup correctly, you should see your node represented by JSON instead of HTML.

For more detailed examples, see GET for updating content entities example.

POST

x_csrf_token=$(curl --silent http://localhost:8888/rest/session/token)

curl --include \
  --request POST \
  --user admin:password \
  --header 'Content-type: application/hal+json' \
  --header "X-CSRF-Token: $x_csrf_token" \
  http://localhost:8888/entity/node?_format=hal_json \
  --data-binary '{"_links":{"type":{"href":"http://localhost:8888/rest/type/node/article"}},"title":[{"value":"My Node Title"}],"type":[{"target_id":"article"}]}'

Notes:

  • This example requires the HAL module
  • For security reasons it is considered bad practice to type passwords directly into your terminal. More secure methods of authentication should be considered.

For more detailed examples, see POST for updating content entities example.

PATCH

function getCsrfToken(callback) {
  jQuery
    .get(Drupal.url('rest/session/token'))
    .done(function (data) {
      var csrfToken = data;
      callback(csrfToken);
    });
}

function patchNode(csrfToken, node) {
  jQuery.ajax({
    url: 'http://localhost:8888/node/1?_format=hal_json',
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/hal+json',
      'X-CSRF-Token': csrfToken
    },
    data: JSON.stringify(node),
    success: function (node) {
      console.log(node);
    }
  });
}

var newNode = {
  _links: {
    type: {
      href: 'http://localhost:8888/rest/type/node/article'
    }
  },
  type: {
    target_id: 'article'
  },
  title: {
    value: 'This is my brand new title'
  }
};

getCsrfToken(function (csrfToken) {
  patchNode(csrfToken, newNode);
});

Notes:

  • This example requires the HAL module
  • This example assumed cookie-based authentication, which means you need to be running under the same domain name.

For more detailed examples, see PATCH for updating content entities example.

DELETE

<?php
$response = \Drupal::httpClient()
  ->delete('http://localhost:8888/node/1?_format=json', [
    'auth' => ['admin', 'password'],
    'body' => '',
    'headers' => [
      'X-CSRF-Token' => $x_csrf_token
    ],
  ]);
?>

Notes:

  • This example assumes you already have the $x_csrf_token value to the value from /rest/session/token.

For more detailed examples, see DELETE for updating content entities example

Exposing Views via Web Services

To expose a view via Web Services:

  1. Edit your view.
  2. Under Displays click + Add and select REST export. Web Services - Views 1
  3. Under Path Settings set a path for your export. Web Services - Views 2
  4. You can adjust various settings in regards to format and fields to display as you would with any other view.
  5. Once you are finished, save your view
  6. Navigate to the path specified above in your browser. If everything went as expected, you should see your via in your specified format: Web Services - Views 3

Additional Resources: