I'm building an HTML page that displays NASA's Astronomy Picture of the Day. Most days the API returns an image, but occasionally it returns a video such as an MP4 or an embedded video page. What's the best way to detect the media type and render the correct element while keeping the media in the same layout container?
3 Answers
Use the API response’s media_type field instead of trying to guess from the URL. If it’s "image", render 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 div and style both consistently.
For direct MP4 files, use a video element with controls. If the video URL points to an external video page, use an iframe instead. You can also use the API’s thumbnail_url when you’d rather show a still image on video days.
Give the wrapper a consistent size and apply shared styles such as max-width, max-height, and object-fit to the image and video. That way the page doesn’t shift dramatically when the daily content changes from an image to a video.

That makes sense. I’ll branch on media_type first and keep both elements inside one styled container.