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}
Comments2
Thanks!!!
Thanks!!!
Excellent
Thank you. This was exactly what I needed to start building a custom API module.