3

We have a content-type that includes a field of type Image. There is also an image file that has been uploaded to Drupal.

We are trying to add new content via a Drupal 8 REST POST. A new node is successfully created when the POST finishes, but the image field is never set. Here is what we are trying:

POST to: http:///entity/node?_format=hal_json
The normal 4 headers are set
POST Body:

{
    "_links": {
    "type": {
      "href": "http://localhost:8087/rest/type/node/product"
    }
  },
    "title": [{"value":"ProductC"}],
    "field_description": [{"value":"ProductC Description"}],
    "field_product_image": [{"src":"/sites/default/files/2017-03/samplelogo_1.jpeg"}],
    "field_product_name": [{"value":"ProductCName"}],
    "field_product_n": [{"value":"prodC"}]
}

Any pointers on how to construct the "field_product_image" line in the payload to link the image to new content node?
Thanks

2
  • Have you tried using target_id instead of src and using the File ID as the value instead? Commented Apr 3, 2017 at 2:59
  • 1
    I had tried target_id before, but used the entire URL for the image. I tried again with just the image ID, and it worked perfectly. Thanks very much!
    – user73048
    Commented Apr 5, 2017 at 21:39

1 Answer 1

2

I tried again with just the image ID, and it worked perfectly. Thanks very much!

To elaborate...

After the image file has been created in Drupal, and you have the File ID you'll be ready to create/update Nodes. Instead of setting the src value on the image field you just need to set the target_id value.

Change this:

"field_product_image": [{"src":"/sites/default/files/2017-03/samplelogo_1.jpeg"}],

To something like this:

"field_product_image": [{"target_id": 123}],

If you're using JavaScript this would typically be accomplished with 2 async calls. The first call would POST the binary file data to Drupal (or base 64 encoded string) to obtain the File ID, the second call (which takes places in the "success" callback of the first call) would then be used to create/update the node's image field with the new File ID.

The following d.o issue is an important one to follow and is very much related to the Question: https://www.drupal.org/node/1927648

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.