A recent internal Commercial Progression project allowed us the opportunity to set up a Drupal 8 site and get REST working on it. In the process, and by merit of the stack being new with the documentation catching up, I learned a few tricks that might be useful for enterprising developers out there.
1. POST-ing entities is to a different path than the REST UI says
If you install the REST UI module and enable an endpoint, you'll see a screen like:
From this display, you might be convinced that the URL you use to HTTP POST a new entity (if the bundle were named "update", for instance) would be
http://yourname.tld/admin/structure/eck/entity/component/update
But you would be wrong. The actual post path is:
http://yourname.tld/entity/component
...where "component" is the entity type. This seems to be the case for pretty much any entity. Don't forget the
?format=haljson
on all your stuff, for good measure.
2. There's a thing called a CSRF token, and you can get one with cURL
The documentation lets you know that risky operations require a CSRF token and how to get one. Yuen Ying Kit even has the necessary Guzzle-based PHP code (posted in 2013!) for grabbing a CSRF token on the fly.
Let's say you wanted to write it for a cURL request in PHP without any external dependencies. That would look something like:
The $csrf_token variable now contains a working token for POST-ing and doing other risky operations.
For a cURL request to do such an operation, your HTTP header should include the following:
As long as you have an acceptable payload in your CURLOPT_POSTFIELDS, you should be off to the races!
3. Entity reference fields work how you would expect, except not
If you GET an entity with an entityreference (Reference? Entity reference?) field as HAL JSON, the result will include a number of interesting tidbits that indicate the reference:
These are all useful payload for interacting with the referenced entities when ingesting, but...
If you format a HAL JSON entity for POST with this structure, the reference field will not populate (at least it didn't for me). The trick is also include a direct value to the desired field, like:
This would add JSON that looks like:
...which the backend will process into the reference. I keep the other HAL stuff along for good measure.
In closing
So that's the stuff I found in my first go at RESTful work in Drupal 8. There's bound to be way more where that came from, and we'll be sure to keep you POSTed with all the gotchas and fun tweaks we find along the way.
Looking to make a Drupal 8 site with lots of web services? Get in touch with the Drupal experts!