Before getting started you will want to make sure you have the following core modules enabled: HAL, HTTP Basic Authentication, RESTful Web Services, and Serialization. These can be found on the modules page under “Web Services.”
To make the set-up process easier we’re going to leverage a contrib module called REST UI. Once installed and enabled, navigate to Configuration>Web services>REST. Here you can see the list of REST resources available by default in Drupal. Enable the “Comment” resource and click “Edit.”
Here you can see the available methods and their settings for this resource. Since we are only dealing with creating and updating comments we only need to enable POST and PATCH methods. Within each method, there are settings for accepted request formats and authentication providers. For this example, we will be using the same settings for POST and PATCH. Enable hal_json for “Accepted request formats” and basic_auth & cookie for “Authentication providers.”
This completes the setup process. We can now begin to write the JS methods needed to POST and PATCH to our REST resources.
To start we are going create a method to authenticate our request with Drupal. This can be found here.
This method is used to get the CSRF Token, which in combination with the session ID, is needed to authenticate requests with Drupal.
When I began looking through Drupal 8 documentation for REST services, specifically relating to comments, the information was not complete. Luckily, others had already started related discussions on the forums and in issue queues.
For creating comments, using POST with a hal+json request format, there are a few extra pieces of information our data object needs before it is sent to our REST resource.
Now that we have the values set up for our data object, newComment, we can actually make the request.
The data object we will be sending to the PATCH resource is much simpler than the one for POST. The same “_links” urls must be sent as before. With hal+json using references, we only need to send the fields we want to update. If we send any read-only fields, such as uid or entity_id, the request will be denied with a 403 response. In this case, our comments only have one field to be updated, the body, so all we have to send is the new value.
Use the same way we fired the POST request to fire the PATCH request:
There you have it. Once everything is enabled, configured, and your variables are where you want them, it actually isn’t too bad to get Drupal’s built-in REST resources to work. A few simple methods and you should be good to go.
Registering Migrations in Drupal 8 | Mediacurrent Blog
8 Insights and Useful Snippets for the D8 Rest Module | Mediacurrent Blog
Migrating From Excel Sheets to Drupal with migrate_spreadsheet | Mediacurrent Blog