How to create a JSON web service on drupal 8 ? | Drupal 8

How to create a JSON web service on drupal 8 ?

Submitted by editor on Tue, 07/25/2017 - 10:33
Question

How to create a custom JSON web service with Drupal 8 ?

This is a simple example of a web service. For the example, We will make a service to multiply two numbers.

Create JSON WebService module

Create a module.

Here : mywebservice

Create route, the Web Service path.

Example:
mywebservice.multiply:
  path: '/mywebservice/maths/multiply'
  defaults:
    _controller: '\Drupal\mywebservice\Controller\MyWebService::multiply'
    _title: 'MyWebService'
  requirements:
    _permission: 'access content'

Create webservice Controller

Example:
<?php
//
namespace Drupal\mywebservice\Controller;
//
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
 * Class MyWebService.
 */
class MyWebService extends ControllerBase {
  /**
   * Multiply.
   */
  public function multiply() {
    $request = \Drupal::request();
    $output['a'] = $request->get('a');
    $output['b'] = $request->get('b');
    $output['result'] = $output['a'] * $output['b'];
    return new JsonResponse($output);
  }
}

Test the web service

Visit : http://yourdomain.loc/mywebservice/maths/multiply
Must return a JSON : {"a":null,"b":null,"result":0}

Visit : http://yourdomain.loc/mywebservice/maths/multiply?a=5&b=2
Must return a JSON : {"a":"5","b":"2","result":10}

 

Add new comment