Problem/Motivation

You can't change the domain name in a JSON API response. A common example would be when JSON API is configured on a Drupal website with the domain www.example.com, however (for a variety of reasons) you'd want the API endpoints to be available through a different domain, for example api.example.com. Responses from JSON API would still use www.example.com in the resource links.

Proposed resolution

Allow the domain to be configured in JSON API Extras settings.
Similar functionality seems to have been implemented in the core Rest module:
https://www.drupal.org/node/2484399

Comments

ericpugh created an issue. See original summary.

ericpugh’s picture

Ugh. I'm not sure how to go about this. At first I was hoping to be able to replace the domain name in the EntityNormalizerTrait, but maybe this would require creating a custom ServiceProvider to replace jsonapi's linkManager?

wim leers’s picture

Category: Feature request » Support request
Status: Active » Fixed
Issue tags: +API-First Initiative

This does not need JSON:API or JSON:API Extras settings. You can achieve this using sites.php, see https://api.drupal.org/api/drupal/sites%21example.sites.php/8.7.x

ericpugh’s picture

Sorry. I should have closed this.

In case it helps anyone else, what I ended up doing is creating an EventSubscriber in a custom module that looks like this:

<?php

namespace Drupal\example_module\EventSubscriber;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
* Event Subscriber ResponseEventSubscriber.
*/
class ResponseEventSubscriber implements EventSubscriberInterface {

  /**
  * Method that is triggered on the response event.
  */
  public function onRespond(FilterResponseEvent $event) {
    $uri = $event->getRequest()->getRequestUri();
    if (substr($uri, 0, 8 ) === "/jsonapi") {
      // Change the domain to proxy (api.example.com) in JSON API response.
      $response = $event->getResponse();
      $content = str_replace(':\/\/example.com\/jsonapi', ':\/\/api.example.com\/', $response->getContent());
      $response->setContent($content);
    }
  }

  /**
  * {@inheritdoc}
  */
  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['onRespond'];
    return $events;
  }
}

Thanks!

wim leers’s picture

That … works. :) But I think #3 would be a lot simpler!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.