In the previous posts, we have gone through some examples about working with Drupal 8 RESTful web service.
- Drupal 8 – Setup the RESTful Service @ 1
- Connect Drupal 8 RESTful Service with Guzzle PHP Web Service Client @ 1
- Drupal 8 – Login in Guzzle Web Service Client @ 1
We can also add node to Drupal through web service. But as i mentioned before, the RESTful feature is not fully completed so we can only create a node with a title. Here is a example web service client in PHP using Guzzle.
<?php require 'vendor/autoload.php'; use Guzzle\Http\Client; use Guzzle\Plugin\Cookie\CookiePlugin; use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar; $cookiePlugin = new CookiePlugin(new ArrayCookieJar()); $client = new Client('http://drupal8.localhost.com'); $client->addSubscriber($cookiePlugin); $client->post('user', null, array( 'name' => '<username>', 'pass' => '<password>', 'form_id' => 'user_login_form', ))->send(); // Extra GET request to retrieve the CSRF protection token. $token = $client->get('rest/session/token')->send()->getBody(TRUE); $node = array( '_links' => array( 'type' => array( 'href' => 'http://drupal8.localhost.com/rest/type/node/article', ), ), 'title' => array( 0 => array( 'value' => 'Article post by RESTful web service', ), ), ); $data = json_encode($node); $client->post('entity/node', array( 'Content-Type' => 'application/hal+json', 'X-CSRF-Token' => $token, ), $data)->send(); ?>
You can create node with different content type by modifying line 23 above. I did try to add a node with body or other custom fields but no luck. There is no way to set the node author neither.
Will update later after the RESTful feature is more completed.
Done =)
Reference: REST: exposing data as RESTful web services
Filed under: CMS, PHP Tagged: Drupal, Drupal 8, Drupal Development, Guzzle, PHP, RESTful, Web Service