Skip to content

Instantly share code, notes, and snippets.

@svetlio
Created July 5, 2026 05:26
Show Gist options
  • Select an option

  • Save svetlio/17e75f59236f0871e7f1390fcd5919ab to your computer and use it in GitHub Desktop.

Select an option

Save svetlio/17e75f59236f0871e7f1390fcd5919ab to your computer and use it in GitHub Desktop.
Rest resource, GET image file in desired "Image style", by file id route parameter, and image_style_name url query parameter
<?php
declare(strict_types=1);
namespace Drupal\custom_fs\Plugin\rest\resource;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\rest\Attribute\RestResource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Represents ImageStyledResource.
*/
#[RestResource(
id: 'custom_fs_imagestyled',
label: new TranslatableMarkup('ImageStyled'),
uri_paths: [
'canonical' => '/api/custom-fs-imagestyled/{id}', // ?image_style_name=thumbnail
],
)]
final class ImageStyledResource extends ResourceBase {
/**
* {@inheritdoc}
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
array $serializer_formats,
LoggerInterface $logger,
private readonly EntityTypeManagerInterface $entityTypeManager,
private readonly RequestStack $requestStack,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): self {
return new self(
$configuration,
$plugin_id,
$plugin_definition,
$container->getParameter('serializer.formats'),
$container->get('logger.factory')->get('rest'),
$container->get('entity_type.manager'),
$container->get('request_stack'),
);
}
/**
* Responds to GET requests.
*/
public function get($id): ResourceResponse {
// Load file by id.
$file = $this->entityTypeManager->getStorage('file')->load($id);
// Get the original image URI.
$original_image = $file->getFileUri();
// Get the image style name.
$image_style_name = $this->requestStack->getCurrentRequest()->query->get('image_style_name');
if (!$image_style_name) {
$image_style_name = 'thumbnail';
}
// Load the image style.
$style = $this->entityTypeManager->getStorage('image_style')->load($image_style_name);
// Get the styled image derivative.
$destination = $style->buildUri($original_image);
$image_styled_url = $style->buildUrl($original_image);
// If the derivative doesn't exist yet (as the image style may have been // added post launch), create it.
if (!file_exists($destination)) {
$style->createDerivative($original_image, $destination);
}
return new ResourceResponse($image_styled_url);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment