Hello, I am trying to access the v2 API with an Academic Research Track profile to query about a Solar Eclipse event that occurred in 2017.

The bearer token was saved in an environment variable: with the below code
os.environ['TOKEN'] = '<ADD_BEARER_TOKEN>'

then created this function:

def auth():
    return os.getenv('TOKEN')

I proceeded to create the following header function.

def create_headers(bearer_token):
    headers = {"Authorization": "Bearer {}".format(bearer_token)}
    return headers

then created the following function for the url…

def create_url(keyword, start_date, end_date, max_results = 10):
    
    search_url = "api v2 endpoint link" #Change to the endpoint you want to collect data from

    #change params based on the endpoint you are using
    query_params = {'query': keyword,
                    'start_time': start_date,
                    'end_time': end_date,
                    'max_results': max_results,
                    'next_token': {}}
             return (search_url, query_params)

Created a function to connect to the endpoint…

def connect_to_endpoint(url, headers, params, next_token = None):
    params['next_token'] = next_token   #params object received from create_url function
    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()

After providing the variables for the query parameters,
I ran this code:

url = create_url(keyword, start_time,end_time, max_results)
json_response = connect_to_endpoint(url[0], headers, url[1])

which returns the following error:

Exception                                 Traceback (most recent call last)
<ipython-input-11-b352318dc621> in <module>
      1 url = create_url(keyword, start_time,end_time, max_results)
----> 2 json_response = connect_to_endpoint(url[0], headers, url[1])

Instead of writing your own code for all this, i recommend using twarc: twarc2 (en) - twarc

Thank you for this.

Let me look it up ASAP.

Best Regards.

1 Like