Học tập Custom controller with JSON response in Drupal 9

26th Jul 2022
Học tập Custom controller with JSON response in Drupal 9
Table of contents

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

add to your module these files like this:

create mymodule.routing.yml

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

create src/Controller/JsonApiArticlesController.php

getData(): 

will return article nodes from database.

<?php
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() {

    $result=[];
    $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:

Bạn thấy bài viết này như thế nào?
1 reaction

Add new comment

Image CAPTCHA
Enter the characters shown in the image.

Related Articles

Under Form Validation Define Counter - Character, Countet Maimum - 1000, Counter Maximum Message - %\%d Characters remaining

Short snippet that shows how to get url parameters in drupal 9. to get query parameter form the url, you can us the following.

Recently I found myself needing to manage cookie data in Drupal 9 for the first time. As oft, my first step in the process was to search through Drupal core and the Drupal API for examples of “the right way” to handle cookies. After I didn’t find any reasonable existing solution within Drupal, it was time to solve this on my own.

Regardless of your position on either side of the web, there is always risk of being a victim of a cyber attack. This has put businesses in a tizz to make personal data of the visitors secure.

we had 5 domain on our website and we need to redirect a user to US domain if user is browsing from US