Tell us about your project

Register user in Drupal 8 using REST API and Web Services

If you want to build an App and want to use Drupal as your back-end, one of the good ways is to use Drupal's RESTful Web services.

First, you have to enable Web Services and Rest UI module (/admin/modules). In Drupal 8 Web Services are already in core, so you need to install only REST UI module to set up REST endpoints. It is recommended to install this module using Composer. So, open the terminal in your Drupal's root directory and type composer require 'drupal/restui:^1.15' (check if 1.15 is the latest stable version).

Read more on: https://www.drupal.org/project/restui. web services

 

In the next step, you have to enable user registration on /admin/webervices/restui. Enable POST, hal_json and json format, and authentication with a cookie like this:

rest user

You also have to access the POST on user registration for the anonymous user:

user registration

Now, everything is ready to create a user using Drupal RESTful API. In this tutorial, we will use jQuery and AJAX to post and get information. There are many tutorials out there on the Web about how to use RESTful API, but when I tried to use any of them, it usually didn't work. I am currently using Drupal version 8.4.4, and the next code worked for me:

  1. Register a user (POST)

    When registering a new user, be sure you are logged out. You have to send headers ('Content-Type': 'application/hal+json', 'Accept': 'application/json') and body in JSON format to 'user/user?_format=hal_json' address:

    var jsonData = {
        "_links": {
            "type": {
                "href": "/rest/type/user/user"
            }
        },
        "name": [
            {"value": name}
        ],
        "mail": [
            {"value": mail}
        ],
        "pass":[
            {"value": pass}
        ],
        "status":[
            {"value": value}
        ]
    }
  1. Log in (POST)

    For "log in" you have to send the headers ('Content-Type': 'application/hal+json', 'Accept': 'application/json') and username / password in JSON format to 'user/login?_format=hal_json' address:

var jsonData = { "name": user, "pass": pass }
  1. If the username and password are correct, you get the response like this:

    response

    If you want to use a CSRF token, you can get it this way:

var csrfToken = response.csrf_token;
  1. Get user information (GET)

    For "get user information", if you logged in, you have to use only user/{uid}?_format=hal_json using a hal+json format for the returned JSON, like so:

    json response

 

4. Log out   

          For "log out" you need to call only 'user/logout'

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


Boldižar Santo