Node::load
Displaying 1 - 1 of 1Custom controller with JSON response
how to create a custom controller with JSON response in Drupal 8.
this might work on Drupal 9 and 10, but I never tested it on these versions.
Code Snippet
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;
}
}
use Symfony\Component\HttpFoundation\JsonResponse;
// if you know the data to send when creating the response
$response = new JsonResponse(['data' => 123]);
// if you don't know the data to send or if you want to customize the encoding options
$response = new JsonResponse();
// ...
// configure any custom encoding options (if needed, it must be called before "setData()")
//$response->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | \JSON_PRESERVE_ZERO_FRACTION);
$response->setData(['data' => 123]);
// if the data to send is already encoded in JSON
$response = JsonResponse::fromJsonString('{ "data": 123 }');