1

I'm trying to follow the example of a custom rest api in https://www.drupal.org/docs/8/api/restful-web-services-api/custom-rest-resources.

I don't understand how I can access the request for get or post. In the example there is only a default response, but I would of course like to make it depending on the request headers and body.

2

The only classes that extend ResourceBase implemented by Drupal core don't check/use what passed in the request. So I could not use Drupal core code as example.

If you really need to access any request value, and the argument passed to the get() or post() methods is not enough/adequate for your purpose, you can inject the request object in the create() static method.

  public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, Request $request) {
    parent:: __construct($configuration, $plugin_id, $plugin_definition,  $serializer_formats, $logger);
    $this->request = $request;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration, 
      $plugin_id, 
      $plugin_definition, 
      $container->getParameter('serializer.formats'), 
      $container->get('logger.factory')->get('rest'),
      $container->get('request_stack')->getCurrentRequest()
    );
  }

In the class methods you then use $this->request to access the request object.

0

You can always get the current request through Drupal::request():

$request = \Drupal::request();
  • Should this be injected? – Kevin Apr 23 '17 at 16:16
  • Depends on context @Kevin, but yeah the request_stack service can be injected to accomplish the same thing – Clive Apr 23 '17 at 16:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.