PATCH with OAuth

Last updated on
17 September 2019

Here is a practical example on how to update a node.

Let's suppose that you have a node with id 56 whose title you want to update through a PATCH request, authenticating the request with OAuth.

Setting up REST

You need to enable the PATCH method with HAL format and OAuth authentication. This can be done easily using REST UI module.

This is what the Content resource looks like after we make the changes at admin/config/services/rest:

REST UI setup

Then, you need to adjust permissions so authenticated users can access the content.

Adjusting permissions

You need to give access to PATCH method to authenticated users, but you also need to allow them to edit the content. These two screenshots show what these permissions should look like:

REST permissions
Content permissions

Finally, you need to set up OAuth credentials for a user in order to make requests.

Setting up OAuth

The full instructions to set up OAuth module can be found on the OAuth authentication page. Once you create the keys for a user, you should see this on the user profile. There, you can copy the key and secret and use it in your script to update the node in the following section.

OAuth consumer

Updating the node

With the above setup, you can make OAuth requests to update content on your Drupal site. Here is a Guzzle script that changes the title of the node with nid 56:

require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Subscriber\Oauth\Oauth1;

$stack = HandlerStack::create();

$middleware = new Oauth1([
  'consumer_key'    => 'yourconsumerkey',
  'consumer_secret' => 'yourconsumersecret',
]);
$stack->push($middleware);

$client = new Client([
  'base_uri' => 'http://d8.local',
  'handler' => $stack,
]);

// Prepare the entity data.
$serialized_entity = json_encode([
  'title' => [['value' => 'Updated node title']],
  'type' => [['target_id' => 'article']],
  '_links' => ['type' => [
      'href' => 'http://d8.local/rest/type/node/article'
  ]],
]);

$response = $client->patch('node/56?_format=hal_json', [
  'auth' => 'oauth',
  'headers' => [
    'Accept' => 'application/hal+json',
    'Content-Type' => 'application/hal+json',
  ],
  'body' => $serialized_entity,
  'debug' => true,
]);

This is the full response from the server when you run this script:

Updating a user

This is an example using the hal_json format to update the email and password:

$serialized_entity = json_encode([
  "_links": {
    "type": {
      "href": "http://d8/rest/type/user/user"
    }
  },
  "mail": [{
    "value": "marthinal@drupalisawesome.com"
  }],
  "pass": [{
    "existing": "existingSecretPass",
    "value": "myNewSuperSecretPass"
  }],
]);

Help improve this page

Page status: No known problems

You can: