Drupal 8 Core includes Restful Web Service module. It builds from Drupal 7 Restful Web Service below are the basic points of the REST in Drupal 8. For the purpose of this article, all the screenshots are for 8.3.x.
Steps To Manage Node Data Through REST:
1. Access http://localhost/admin/config/services/rest for listing all links of REST UI.
Click on configure link, you will see the following screen. Please click on Edit link for configuration of this link.
After that, you will see following configuration for that specific REST.
Click on configure link, you will see the following screen. Please click on Edit link for configuration of this link.
After that, you will see following configuration for that specific REST.
1. GET request: You can get node detail page using following code.
<pre>
$client =$this->http_client;
$response = $client ->get('http://localhost/node/1?_format=json');
$json_string = json_decode($response->getBody());
</pre>
2. POST request: You can add node using X-CSRF token.
/* Get Session Token Start Code */
$client =$this->http_client;
$response = $client
->get('http://localhost:8888/drupal-8.3.4/rest/session/token');
$token_string = (string) ($response->getBody()) ;
/* Get Session Token End Code*/
$serialized_entity = json_encode([
'title' => [['value' => 'Example Article']],
'type' => [['target_id' => 'article']],
'_links' => ['type' => [
'href' => 'http://localhost/rest/type/node/article'
]],
]);
$response = $client
->post('http://localhost/entity/node?_format=hal_json', [
'auth' => ['user', 'password’],
'body' => $serialized_entity,
'headers' => [
'Content-Type' => 'application/hal+json',
'X-CSRF-Token' => $token_string
],
]);
3. Update Request: You can update details of node id = 1 using following code.
<pre>
/* Get Session Token Start Code */
$client =$this->http_client;
$response = $client
->get('http://localhost:8888/drupal-8.3.4/rest/session/token');
$token_string = (string) ($response->getBody()) ;
/* Get Session Token End Code*/
$serialized_entity = json_encode([
'title' => [['value' => 'Example Article UPDATED']],
'type' => [['target_id' => 'article']],
'_links' => ['type' => [
'href' => 'http://localhost/rest/type/node/article'
]],
]);
$response = $client
->patch('http://localhost/node/1?_format=hal_json', [
'auth' => ['user', 'password’],
'body' => $serialized_entity,
'headers' => [
'Content-Type' => 'application/hal+json',
'X-CSRF-Token' => $token_string
],
]);
</pre>
4. Delete request: You can delete node = 1 using following code.
<pre>
/* Get Session Token Start Code */
$client =$this->http_client;
$response = $client
->get('http://localhost/rest/session/token');
$token_string = (string) ($response->getBody()) ;
/* Get Session Token End Code*/
$response = $client
->delete('http://localhost/node/1?_format=hal_json', [
'auth' => ['user', 'password’],
'headers' => [
'X-CSRF-Token' => $token_string
],
]);
</pre>