Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting instagram post url from media id

Tags:

api

instagram

I have the post media_id in my hands and I'd like to know if there is a way to create a valid url from it.

For instance, if you have a Facebook post id (xxxx_yyyy) on your hands, you can create the following url from it (http://facebook.com/xxxx/posts/yyyy) and directly access the original post.

Is there a way to do this on Instagram? Having media_id (and user_id) in my hands, is it possible to create a single post url?

like image 706
magroski Avatar asked Dec 08 '22 07:12

magroski


1 Answers

I had to implement client side javascript to solve this and Seano's answer was invaluable and I was glad they mentioned the use of the BigInteger library however I wanted to provide a complete implementation using the BigInteger library which as it turns out is quite necessary.

I downloaded the BigInteger lib from https://www.npmjs.com/package/big-integer.

Here is the function which works well for me.

function getInstagramUrlFromMediaId(media_id) {
    var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
    var shortenedId = '';
    media_id = media_id.substring(0, media_id.indexOf('_'));

    while (media_id > 0) {
        var remainder = bigInt(media_id).mod(64);
        media_id = bigInt(media_id).minus(remainder).divide(64).toString();
        shortenedId = alphabet.charAt(remainder) + shortenedId;
    }

    return 'https://www.instagram.com/p/' + shortenedId + '/';
}

I just want to point out that the usage of toString() when assigning the re-calculated media_id is very important, the value remains a string to ensure the entire number is used (in my case the media_id was 19 characters long). The BigInteger documentation also states this...

Note that Javascript numbers larger than 9007199254740992 and smaller than -9007199254740992 are not precisely represented numbers and will not produce exact results. If you are dealing with numbers outside that range, it is better to pass in strings.

Cheers!

like image 190
Nick Hanshaw Avatar answered Dec 26 '22 04:12

Nick Hanshaw