Marco Liedecke
Marco Liedecke

Reputation: 241

Extract list of Twitter follower IDs using Tweepy API v2: Exception 400

I am simply trying to extract the followers of a Twitter profile using the following code. However, for some unknown reason, the id query parameter value is not valid. I have tried to input the user id of several Twitter accounts to see if the problem lied with the id rather than my code. The problem is in the code...

def create_url_followers(max_results):
    # params based on the get_users_followers endpoint
    query_params_followers = {'max_results': max_results,  # The maximum number of results to be returned per page
                              'pagination_token': {}}  # Used to request the next page of results
    return query_params_followers


def connect_to_endpoint_followers(url, headers, params):
    response = requests.request("GET", url, headers=headers, params=params)
    print("Endpoint Response Code: " + str(response.status_code))
    if response.status_code != 200:
        raise Exception(response.status_code, response.text)
    return response.json()


# Inputs for the request
bearer_token = auth() # retrieves the token from the environment
headers = create_headers(bearer_token)
max_results = 100 # number results i.e. followers of pol_id

To run the code in a for loop I add the id in the position for id in the URL and loop through the list of ids while appending results to the json_response_followers.

pol_ids_list = house["Uid"].astype(str).values.tolist() # create list of politician ids column Uid in df house.

json_response_followers = [] # empty list to append Twitter data
for id in pol_ids_list: # loop over ids in list pol_ids_list
    url = (("https://api.twitter.com/2/users/" + id + "/followers"), create_url_followers(max_results))
    print(url)
    json_response_followers.append(connect_to_endpoint_followers(url[0], headers, url[1])) # append data to list json_response_list

    sleep(60.5)  # sleep for 60.5 seconds since API limit is 
    pass

Upvotes: 1

Views: 1043

Answers (1)

anon
anon

Reputation:

I think the problem here could be that you're specifying pol_id as a parameter, which would be appended to the call. In the case of this API, you want to insert the value of pol_id at the point where :id is in the URL. The max_results and pagination_token values should be appended.

Try checking the value of url before calling connect_to_endpoint_followers.

I think you are currently trying to call

https://api.twitter.com/2/users/:id/followers?id=2891210047&max_results=100&pagination_token=

This is not valid, as there's no value for :id in the URI where it belongs, and the id parameter itself is not valid / is essentially a duplicate of what should be :id.

It should be:

https://api.twitter.com/2/users/2891210047/followers?max_results=100&pagination_token=

Upvotes: 1

Related Questions