Tell us about your project

Drupal 8 logo

If you still don't have the Web Services and Rest UI modules on your Drupal website, you can see how to add them to web services.

If you do have them, let's see how to CRUD a node using Drupal’s Web Services.

You have to enable Get, Create, Update, and Delete node on /admin/webservices/restui.

Also enable hal_json and json format, and authentication with a cookie:

REST services

1. Create node (POST)

To create a node using the API, you'd first want to approve a permission for authenticated users to create nodes (/admin/people/permissions):

create content permission

 

CSRF token for the current user, and body in the JSON format. You can get CSFR token from /rest/session/token for the currently logged in or anonymous user:

// Get token for the current user
$.get('http:// yourwebsite/rest/session/token').done(function(response) {
    var csrfToken = response;
});

 

For creating a node you need to send headers (Content-Type': 'application/hal+json', 'Accept': 'application/json' and 'X-CSRF-Token': csrfToken) using a POST method to '/node?_format=hal_json'.

The body JSON data is like this:

var jsonData = {
    "_links": {
        "type": {
            "href": "http:// yoursite/rest/type/node/article"
        }
    },
    "title": [ {
        "value": "nodeTitle"
    } ],
    "body": [ {
        "value": "nodeBody"
    } ]
}

If the call is successful, you'll need to receive the next result:

response

2. Get Node (GET)

For fetching a node you'll want to use only a node ID and hal+json format:

// Get a node using node id
$.get("http:// yourwebsite/node/{nid}?_format=hal_json").done(function(response) {
    var nodeJson = response;
});

3. Update Node (PUT)

For node update you'll want to approve a permission for authenticated users to modify their own nodes, and you'll also need a node id and a CSRF token for the current user. Send headers ('Content-Type': 'application/hal+json', 'Accept': 'application/json' and 'X-CSRF-Token': csrfToken) and a JSON body to /node/{nid}?_format=hal_json' using the PUT method.

var jsonData = {
    "_links": {
        "type": {
            "href": "http:// yourwebsite /rest/type/node/article"
        }
    },
    "title": [ {
        "value": "nodeTitle"
    } ],
    "body": [ {
        "value": "nodeBody"
    } ]
}

4. Delete Node (DELETE)

For deleting a node you'll want to approve a permission for authenticated users to delete their own nodes, and you'll also need a node ID and a CSRF token for the current user. Send headers ('Content-Type': 'application/hal+json', 'Accept': 'application/json' and 'X-CSRF-Token': csrfToken) and a JSON body to /node/{nid}?_format=hal_json' using the DELETE method.

var jsonData = {
    "_links": {
        "type": {
            "href": "http:// yourwebsite/rest/type/node/article"
        }
    }
}

 

If you want to try the code from this tutorial, you can download it from here.


Boldižar Santo