I'm building an HTML page that displays NASA's Astronomy Picture of the Day. Most days the API returns an image, but some days it returns a video, such as an MP4 or an embedded video page. What's the best way to detect the media type and display the correct element in the same consistent area of the page?
3 Answers
Use the API response’s media_type field instead of trying to infer the format from the URL. If it’s "image", create an img element; if it’s "video", render a video element or an iframe depending on the returned URL. Put either element inside the same wrapper and style the wrapper so the page layout stays consistent.
For video entries, check whether the URL points directly to an MP4. Direct files work well with a video element and controls, while YouTube or other hosted pages are usually better shown in an iframe. The API may also provide a thumbnail_url if you want to show a still image instead.
Keep both media types inside one container and apply shared CSS, such as a maximum height or aspect ratio, width: 100%, and object-fit: contain. That prevents the page from jumping around when the daily content changes from an image to a video.

That makes sense. I’ll use media_type to choose the element dynamically and keep both options inside the same styled container.