TD Ameritrade - The API key in request is either null or blank or invalid

To get an oauth access token or refresh token from the TD Ameritrade API in Python, you may try to use normal query parameters like the following:

r = requests.post(
    f'https://api.tdameritrade.com/v1/oauth2/token?grant_type=refresh_token&refresh_token={refresh_token}&access_type=&code=&client_id=MYAPIKEY@AMER.OAUTHAP&redirect_url=http://localhost',
    }
)

However, this will result in the following error:

{'error': 'The API key in request is either null or blank or invalid.'}

Instead of using query parameters, use the data argument, which will submit it as x-www-form-urlencoded form data:

r = requests.post(
    'https://api.tdameritrade.com/v1/oauth2/token',
    data={
        'grant_type': 'refresh_token',
        'refresh_token': refresh_token,
        'client_id': 'MYAPIKEY@AMER.OAUTHAP',
    }
)

Comments

Add Comment

Name

Email

Comment

Are you human? * seven = 14