Tschareck
Tschareck

Reputation: 4239

Get Twitter card from API

I would be able to retrieve HTML markup of what is stored in Twitter Card (https://dev.twitter.com/docs/cards).

Up until now I used TweetSharp library to retrieve tweets from some user's timeline. But, what is not surprising, because cards are new thing, it is not included.

Does anyone know, if it is possible to access card (data cached by Twitter crawler) with API?

Upvotes: 9

Views: 2353

Answers (2)

Ghan
Ghan

Reputation: 351

Twitter apis do not provide the twitter-card info out of the box. You can extract the card info for a url by looking it up in its html. Below code in csharp gets card image src from the url-

public static TweetMedia[] GetTwitterCardDetails(string url)
    {
        string HTML;
        using (var wc = new WebClient())
        {
            HTML = wc.DownloadString(url);
        }
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(HTML);
        
        HtmlNode element = doc.DocumentNode.SelectSingleNode("//meta[@name='twitter:image:src']");
        if (element != null)
        {
            return new TweetMedia[] { new TweetMedia { url=url, media_url_https = element.Attributes["content"].Value, type = TweetTypes.TweetType.Photo.ToString() } };
        }   
        return null;            
    }

Upvotes: 2

Terence Eden
Terence Eden

Reputation: 14334

The Twitter cards themselves are not exposed through the Twitter API.

What you'll need to do is make a request to the URL mentioned and examine the <head> element to see if they have the Twitter Card info in there.

Upvotes: 8

Related Questions