Extracting data from HubSpot using Python

Hi, I am a complete beginner in using APIs and extracting data but has been given a task to create a POC of extracting data from hubSpot. But the issue is I keep getting this message.

Error obtaining access token: 400 - {“status”:“BAD_AUTH_CODE”,“message”:“missing or unknown auth code”

The code being returned is None. Not sure what I am doing wrong, the Client ID, Client secret and redirect URL are all ok. Here is the code

from flask import Flask, request

import requests

app = Flask(__name__)

# OAuth 2.0 credentials

CLIENT_ID = ‘’

CLIENT_SECRET = ‘’

REDIRECT_URI = ‘http://localhost

@app.route(‘/callback’)

def callback():

authorization_code = request.args.get(‘code’)

# Prepare payload for token request

payload = {

‘grant_type’: ‘authorization_code’,

‘client_id’: CLIENT_ID,

‘client_secret’: CLIENT_SECRET,

‘redirect_uri’: REDIRECT_URI,

‘code’: authorization_code

}

print(“Token Request Payload:”, payload) # Print the payload

# Make request to HubSpot token endpoint

token_url = ‘https://api.hubspot.com/oauth/v1/token

response = requests.post(token_url, data=payload)

if response.status_code == 200:

access_token = response.json().get(‘access_token’)

# Use the access token to make requests to HubSpot API

if access_token:

headers = {

‘Authorization’: f’Bearer {access_token}',

‘Content-Type’: ‘application/json’

}

endpoint = ‘https://api.hubapi.com/crm/v3/objects/contacts

response = requests.get(endpoint, headers=headers)

if response.status_code == 200:

data = response.json()

return str(data)

else:

return f’Error: {response.status_code} - {response.text}’

else:

return ‘Access token not found in response’

else:

return f’Error obtaining access token: {response.status_code} - {response.text}’

if __name__ == ‘__main__’:

app.run(debug=True)

I am using a developer’s account

Hi @aqsa31 :waving_hand:

Have you inspected the value of your variable “authorization_code”? The reason I ask is that this error response occurs when the supplied authorisation “code” is either missing or not correct. I suspect there might be something going on with your redirect URL and the query parameter “code” returned by HubSpot after app permissions are approved during the install flow. Another easy way to check this would be to swap:

authorization_code = request.args.get('code')

for:

authorization_code = request.args['code']

If “code” is not present as a query parameter, this should lead to a KeyError (or similar).

I hope this proves useful. Please let me know if you have any follow-up questions.