function RestExampleClientCalls::create

Same name in other branches
  1. 4.0.x modules/rest_example/src/RestExampleClientCalls.php \Drupal\rest_example\RestExampleClientCalls::create()

Create a node on the remote server, using POST.

Parameters

array $node: Contains the data of the node we want to create.

Return value

\Symfony\Component\HttpFoundation\Response A HTTP response.

Throws

\InvalidArgumentException

\GuzzleHttp\Exception\GuzzleException

File

modules/rest_example/src/RestExampleClientCalls.php, line 127

Class

RestExampleClientCalls
Here we interact with the remote service.

Namespace

Drupal\rest_example

Code

public function create(array $node) {
    if (empty($this->remoteUrl)) {
        return new Response('The remote endpoint URL has not been setup.', 500);
    }
    // Build an array of options telling the remote server what type of content
    // we want to create, and give it a title. After that, we encode it all
    // to JSON.
    $request_body = json_encode([
        '_links' => [
            'type' => [
                'href' => $this->remoteUrl . '/rest/type/node/' . $node['type'],
            ],
        ],
        'title' => [
            0 => [
                'value' => $node['title'],
            ],
        ],
    ]);
    $response = $this->client
        ->request('POST', $this->remoteUrl . '/entity/node', [
        'headers' => $this->clientHeaders,
        'auth' => $this->clientAuth,
        'body' => $request_body,
    ]);
    // Validate the response from the remote server.
    if ($response->getStatusCode() != 201) {
        return new Response('An error occurred while creating the node.', 500);
    }
}