Search code examples
pythonpandaspython-requestsget

Unable to connect with EIA api url


I'm trying to retrieve data via EIA api url with the get method but unable to establish connection.

data URL= https://www.eia.gov/opendata/browser/petroleum/pri/spt?frequency=daily&data=value;&facets=series;&series=RWTC;&sortColumn=period;&sortDirection=desc;

import pandas as pd
import requests
call_eia = requests.get("https://api.eia.gov/v2/petroleum/pri/spt/data/?frequency=daily&data[0]=value&facets[series][]=RBRTE&sort[0][column]=period&sort[0][direction]=desc&offset=0&length=5000")

print(call_eia)

currently getting <Response [403]> as output of print


Solution

  • Hitting the URL passed to requests.get returns the self-explanatory message:

    API_KEY_MISSING No api_key was supplied. Please register for one at https://www.eia.gov/opendata/register.php

    As described in API Technical Documentation you need to insert api_key parameter to the request:

    import requests
    
    params = {'api_key': 'your_api_key'}
    call_eia = requests.get("https://api.eia.gov/v2/petroleum/pri/spt/data/?frequency=daily&data[0]=value&facets[series][]=RBRTE&sort[0][column]=period&sort[0][direction]=desc&offset=0&length=5000", params=params)
    
    print(call_eia)
    

    The documentation also describes how to obtain the API key.