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}

 

Comments

Will Peavy (not verified)

Fri, 04/27/2018 - 06:15

Thank you. This was exactly what I needed to start building a custom API module.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.