Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

How to create a JSON web service on drupal 8 ?

By editor , 25 July, 2017
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}

 

File
mywebservice.zip (2.43 KB)

Tags

  • Drupal 8
  • Code
  • Module
  • WebService
  • Add new comment
Drupal 8 RESTful Web Services
Create a simple module for Drupal 8 - Step 2 - Create Simple Page

Comments2

Plain text

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

Drupalist (not verified)

8 years 8 months ago

Thanks!!!

Thanks!!!

  • Reply

Will Peavy (not verified)

8 years 7 months ago

Excellent

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

  • Reply

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer