Search code examples
react-nativeaxiosfetch-apireact-native-fetch-blobrn-fetch-blob

How to Get json.json file From Twitter Embed API in React Native App


According to the Twitter docs, in order to embed a twitter video into an app, you have to use their embed endpoint like so: https://publish.twitter.com/oembed?url=${enter_twitter_video_url}.

Example: https://publish.twitter.com/oembed?url=https://twitter.com/infinite_red/status/1507392896739151882

The strange thing about this is that it doesn't act like normal embed links where you get a json response from a fetch call. It actually triggers a json.json download in the browser. Within that file, it contains the embed link. That obviously complicates things from a code perspective. If it just sent a json response using axios or apisauce, it would be easy to parse the response for the embed link. Instead it is actually within a file that you have to download.

I attempted to use rn-fetch-blob to grab this json file, but it grabs empty state html data from the twitter page instead. Anyone have any idea how to accomplish this?

I've also tried a few out of date libraries that don't work either, as this json download issue must be a newer change from twitter. It used to be an actual json response.

Twitter embed docs:

https://developer.twitter.com/en/docs/twitter-for-websites/timelines/guides/oembed-api

https://developer.twitter.com/en/docs/twitter-for-websites/embedded-tweets/overview

This has been a full day of struggle, thanks in advance...


Solution

  • You need to encodeURIComponent the link. Then the response will give you clean JSON.

    export const getTwitterEmbed = async (tweet_post) => {
    
        const post_url = tweet_post
    
        try {
            const response = await fetch(
    
                `https://publish.twitter.com/oembed?url=${encodeURIComponent(post_url)}`,
                {
                    headers: {
                        Accept: 'application/json; charset=utf-8'
                    }
                }
            )
            const post = await response.json()
    
    
            return post
    
        } catch (error) {
            console.log(error);
            return error
        }
    }