Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

in this article, I'll show you how to create custom controller with JSON response in Drupal 8.

add to your module these files like this:

create mymodule.routing.yml

  path: '/api/articles'
    _controller: 'Drupal\mymodule\Controller\JsonApiArticlesController::index'
    _title: 'Codimth JSON api'
  methods:  [GET]
    _access: 'TRUE'

create src/Controller/JsonApiArticlesController.php

getData(): will return article nodes from database.

namespace Drupal\mymodule\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;

 * Class JsonApiArticlesController
 * @package Drupal\mymodule\Controller
class JsonApiArticlesController {

   * @return JsonResponse
  public function index() {
    return new JsonResponse([ 'data' => $this->getData(), 'method' => 'GET', 'status'=> 200]);

   * @return array
  public function getData() {

    $query = \Drupal::entityQuery('node')
      ->condition('type', 'article')
      ->sort('title', 'DESC');
    $nodes_ids = $query->execute();
    if ($nodes_ids) {
      foreach ($nodes_ids as $node_id) {
        $node = \Drupal\node\Entity\Node::load($node_id);
        $result[] = [
          "id" => $node->id(),
          "title" => $node->getTitle(),
    return $result;


/api/articles will return result like this:

json api




Add new comment

Restricted HTML


Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.


Contact Us

All the content is FREE but I still need your help


Become a patreon