jsonjson-apidrupal-10jsonapi-extras

How to get Media image url link rendered in JSON:API response


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?


Solution

  • Please use the following path. 'field_image' is the article machine name. 'field_media_image' is the relationship field name from the included.

    '/jsonapi/node/article?include=field_image.field_media_image';
    

    You will find the image URL under 'included' in the 'file--file' type 'attributes.uri.url'

    Please share better option