Pimcore4 Custom REST-API-endpoint for React


#1

This is the first time I use React in combination with Pimcore (version 4, as i am updating an older site). As I understood, correct me if I am wrong, I need to create custom REST endpoints which can be fetched from React. This seems straight forward, although I run into some troubles:

  1. I am correct to extend from /pimcore/modules/webservice/controllers/RestController.php?
  2. Were do i register the custom endpoint to the class? Maybe in startup.php?

Any advice, help is welcome.

Related but different version: How to add rest api end point


#2

no, don’t change the core, just create a new controller and add the actions there.


#3

I’m not sure the solution/sourcecode in pimcore v4 because I’m using pimcore v5.
In version 5, my class controller extend from \pimcore\lib\Pimcore\Bundle\AdminBundle\Controller\Rest\AbstractRestController.php

Then in every action method, I defined routing as below:

image

Hope this helpful


#4

Thanks for sharing. I did the following:

  1. I extended from Pimcore\Controller\Action Controller and put it in the \website\controllers folder.
use Pimcore\Model\Object;
use Pimcore\Controller\Action;
use Pimcore\Model\Webservice;

class ReactController extends Action
{

    private $encoder;
    private $status_options;

    public function init(){
        parent::init();
        $this->encoder = new Webservice\JsonEncoder();
        $this->status_options = Object\Service::getOptionsForSelectField(
            new Object\Student(), "Status"
        );
    }

    public function projectsAction(){
        $this->disableViewAutoRender();
        
        // do stuff

        // return JSON
        $this->encoder->encode([
            "project" => "some_payload"
        ]);
    }

  1. I added the following to \website\config\startup.php
$front = \Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$routeCustom = new \Zend_Controller_Router_Route(
    'project-data',
    array(
        "controller" => "React",
        "action" => "Projects"
    )
);
$router->addRoute('project-data', $routeCustom);
$front->setRouter($router);