instagraminstagram-apiinstagram-graph-api

How to figure out an Instagram username from the user id


I am working on a program that needs to scrape information from the public Instagram API.

My code is using the endpoint https://instagram.com/{username}/?__a=1 to get information about a user and in order to uniquely identify Instagram accounts even after name changes I store the "id" parameter that always stays the same.

Up to this point, it was possible to use another Instagram API Endpoint https://i.instagram.com/api/v1/users/{id}/info/ to find out the current username connected to a given account but it has been removed by Instagram a few days / weeks ago.

I'd highly appreciate if anyone knows another way of getting a username from a user id since I was not able to find one myself nor find a solution by someone else online.


Solution

  • Ig has changed this endpoint behavior and it's been secured. However, the hint here is the error message

    {
    "message": "useragent mismatch",
    "status": "fail"
    }
    

    Passing a valid useragent you can skip this new security-check. Let me share a piece of python code

    import requests
    def get_user_by_user_id(user_id):
        user = {}
        if user_id:
            base_url = "https://i.instagram.com/api/v1/users/{}/info/"
            #valid user-agent
            headers = {
                'user-agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Instagram 105.0.0.11.118 (iPhone11,8; iOS 12_3_1; en_US; en-US; scale=2.00; 828x1792; 165586599)'
            }
            try:
                res       = requests.get(base_url.format(user_id),headers=headers)
                user_info = res.json()
                user      = user_info.get('user',{})
            except Exception as e:
                print("getting user failed, due to '{}'".format(e.message))
        return user
    
    user_id=<your_user_id>
    get_user_by_user_id(user_id) #ta-dah!
    

    There should be some pluggin that allow you change headers in order to get results throught a browser request...