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
You can use the below code to get the url value
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]
Please share better options.