Using the following code we can post a node trough rest API. However, if there is an image attached to this article we need to post the image node first and then include the image fid in the article.I successfully posted the image also but as far as the documentation is very incomplete I am not able to find a way to add the image fid to the second request to attach it to the article.

$serialized_entity = json_encode([
   'title' => [['value' => $node->title]],
   'body' => $node->body_array,
   'type' => [['target_id' => $node->node_type]],
   '_links' => ['type' => [
       'href' => $base_url.'/rest/type/node/'. $node->node_type

$response = \Drupal::httpClient()
    ->post($base_url.'/entity/node?_format=hal_json', [
        'body' => $serialized_entity,
        'headers' => [
            'Content-Type' => 'application/hal+json',
            'Authorization' => 'Bearer '. $token->access_token

Is this the right way to attach an image? if yes, what are the request parameters we need to add the image to the node post request?

Any help would be appreciated. Thanks

1 Answer 1


See https://www.drupal.org/project/drupal/issues/1927648, this is not supported yet in core.

You can try using https://www.drupal.org/project/better_normalizers to send it base64 encoded instead.

  • Thanks Berdir, the better_normalizer module has no documentation. May you please post an example of how it can be used. However, I could manage to send the files with JSON API. My problem is how to make a relation between the image and the article since I am creating them separately via the web service.
    – Hedeshy
    Feb 4, 2018 at 15:44
  • For better normalizers, use GET on a file to see an example. Don't know about JSON API, but a file/image is basically the same as an entity reference. You reference the file you created with the UUID. the core issue I linked has test coverage doing that using the new upload API but that part remains the same
    – Berdir
    Feb 5, 2018 at 10:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.