Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rjcorwin/061f46e82f8663d0c83c to your computer and use it in GitHub Desktop.
Save rjcorwin/061f46e82f8663d0c83c to your computer and use it in GitHub Desktop.

RESTful Drupal 8 CRUD Example using jQuery and core REST module

CREATE Item

var package = {}
package.title = [{'value':'t1'}]
package.body = [{'value':'b1'}]
package._links = {"type":{"href":"http://local.drupal8.org/rest/type/node/page"}}

$.ajax({
  url: "http://local.drupal8.org/entity/node",
  method: "POST",
  data: JSON.stringify(package),
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/hal+json"
  },
  success: function(data, status, xhr) {
    debugger
  }
})

GET Item

$.ajax({
  url: "http://local.drupal8.org/node/3",
  method: "GET",
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/hal+json"
  },
  success: function(data, status, xhr) {
    debugger
  }
})

GET an Item and then UPDATE Item

$.ajax({
  url: "http://local.drupal8.org/node/3",
  method: "GET",
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/hal+json"
  },
  success: function(data, status, xhr) {
    var package = {}
    package.title = data.title
    package.body = data.body
    package.title[0].value = 'yar'
    package._links = {"type":{"href":"http://local.drupal8.org/rest/type/node/page"}}
    debugger

    $.ajax({
      url: "http://local.drupal8.org/node/3",
      method: "PATCH",
      data: JSON.stringify(package),
      headers: {
        "X-CSRF-Token": "niCxgd5ZZG25YepbYtckCy7Q2_GL2SvMUY5PINxRAHw",
        "Accept": "application/json",
        "Content-Type": "application/hal+json"
      },
      success: function(data, status, xhr) {
        debugger
      }
    })

  }
})

DELETE Item

$.ajax({
  url: "http://local.drupal8.org/node/3",
  method: "DELETE",
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/hal+json"
  },
  success: function(data, status, xhr) {
    debugger
  }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment