Retrieving URL to DAM Files from Drupal/PHP Code

Created on 18 June 2025, about 2 months ago

Problem/Motivation

It is difficult to understand how to retrieve external urls to files which are stored in the DAM in a programmatic way, either via Twig or PHP.

Some use cases:

  1. when using Linkit and Linkit Media Library in CKEditor5 - how can we get the full URL to the remote image?
  2. when trying to set a variable for use in twig, i.e. background_image or something

Steps to reproduce

  1. Install and configure the DAM
  2. Import some media items into Drupal
  3. Try to get a URL to the source file programmatically

Proposed resolution

TBD

Remaining tasks

TBD

Current Workaround

My current approach to handling this is to create a new service in Drupal that connects to the API. The method looks like this:

  public function getAssetDamUrl(string $asset_id, string $format = 'original'): string {
    $search_url = $this->getAssetLookupUrl($asset_id);
    $access_token = $this->settings->get('dam_access_key');
    $headers = [
      'Authorization' => "Bearer " . $access_token,
    ];
    try {
      $request = $this->httpClient->request('GET', $search_url, ['headers' => $headers]);
      $item_data = json_decode($request->getBody()->getContents(), TRUE);
      return $item_data['embeds'][$format]['url'] ?? "";
    }
    catch (RequestException $e) {
      return "";
    }
  }

But I wonder if:

  1. Is it worthwhile to add a new service into Acquia Dam for this purpose?
  2. Is there a better/more efficient way?
💬 Support request
Status

Active

Version

1.1

Component

Code

Created by

🇺🇸United States dan612 Portland, Maine

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @dan612
  • 🇮🇳India rajeshreeputra Pune

    Try using getAsset($asset_id) method.

    $asset_data = \Drupal::service('acquia_dam.client.factory')->getSiteClient()->getAsset($asset_id);
    if ($asset_data) {
      $asset_url = $asset_data['embeds']['original'];
    }
    
Production build 0.71.5 2024