How to get image url from tweets using the Twitter API

To get the media_url back to twitter search pass tweet_mode=extended. Works across multiple endpoints (eg. /statuses/show, /statuses/user_timeline ..)

Example: https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=aneon&tweet_mode=extended

More here: https://developer.twitter.com/en/docs/tweets/tweet-updates.html


Tweet Entities are what you are looking for to access the pictures. Entities provide structured data from Tweets including expanded URLs and media URLs. They are located under the entities attribute in all Tweet objects from both Twitter REST and Streaming APIs.

As a result, to answer your question, if a Tweet contains one picture, its URL will be located here:

$media_url = $result->entities->media[0]->media_url;

Below is a PHP snippet you can add to your existing foreach loop, it is a bit more elaborate to handle whether or not the Tweet contains media URLs:

if (isset($result->entities->media)) {
    foreach ($result->entities->media as $media) {
        $media_url = $media->media_url; // Or $media->media_url_https for the SSL version.
    }
}

To get the image url of a Tweet with the new v2 api you must append expansions=attachments.media_keys&media.fields=url at your url. For example to open a stream that returns tweets with their images(if any) create a get request like this

https://api.twitter.com/2/tweets/search/stream?tweet.fields=created_at&expansions=attachments.media_keys&media.fields=url

Tags:

Image

Url

Twitter