skip to Main Content

I am trying to get the URL of the media image served via JSON to the frontend, but I’m unable to do so. My expected output is the following.

{
    "data": {
        "type": "media--image",
        "id": "1900srf-asdf-3456-djh4-sakjfdhdsakfhsla3",
        "attributes": {
            "field_media_image": [
                {
                    "url": "/sites/default/files/styles/heor_banner_image_style/public/2024-09/generateImage.png",
                    "alt": "Description of the image"
                }
            ]
        }
    }
}

I currently run a Drupal 10 site where I have a banner image field which references a media image. I am getting relationships in my JSON data, but I am unable to flatten out the image field.

I read that if I use json extra I can override the output by using Single nested property. For some reason I am unable to show the URL.

Can I get some guidance on how to get the URL on the JSON, so that I can use it in frontend?

2

Answers


  1. You can use the below code to get the url value

    <?php
    $txt = '{ "data": { "type": "media--image", "id": "1900srf-asdf-3456-djh4-sakjfdhdsakfhsla3", "attributes": { "field_media_image": [ { "url": "/sites/default/files/styles/heor_banner_image_style/public/2024-09/generateImage.png", "alt": "Description of the image" } ] } } }';
    $json = json_decode($txt);
    print($json->data->attributes->field_media_image[0]->url);
    
    Login or Signup to reply.
  2. I created a separate function that returns the image URL, where you must pass the image id. On the function I fetch images from media–image (media library) using the path ‘jsonapi/media/image?include=field_media_image’. [imageId = included[0].relationships.field_media_image.data.id]

     const retriveImageMedia = async (ImageId) => {
      const response = await axios.get(`${baseurl.url}/jsonapi/media/image/${ImageId}?include=field_media_image&fields[file--file]=uri,url`,
      {headers:{
        "Accept": "application/vnd.api+json"
      }})
      return response.data;
    }
    

    Please share better options.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search