pythonpython-3.xgoogle-ads-api

Google API refresh token is None when requesting tokens


I have followed the guide below to obtain a Google Ads API refresh token for my application.

https://github.com/googleads/googleads-python-lib/wiki/API-access-on-behalf-of-your-clients-(web-flow)

Using the script below, everything worked, but the response only had an access token, while the refresh token was None.

from googleads import oauth2
import google.oauth2.credentials
import google_auth_oauthlib.flow


# Initialize the flow using the client ID and secret downloaded earlier.
# Note: You can use the GetAPIScope helper function to retrieve the
# appropriate scope for AdWords or Ad Manager.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    'client_secret.json',
    [oauth2.GetAPIScope('adwords')])
# Indicate where the API server will redirect the user after the user completes
# the authorization flow. The redirect URI is required.
flow.redirect_uri = 'https://www.example.com'

# Generate URL for request to Google's OAuth 2.0 server.
# Use kwargs to set optional request parameters.
authorization_url, state = flow.authorization_url(
    # Enable offline access so that you can refresh an access token without
    # re-prompting the user for permission. Recommended for web server apps.
    access_type='offline',
    # Enable incremental authorization. Recommended as a best practice.
    include_granted_scopes='true',
    # approval_prompt='force'
)
print("\n" + authorization_url)
print("\nVisit the above URL and grant access. You will be redirected. Get the 'code' from the query params of the redirect URL.")

auth_code = input('\nCode: ').strip()

flow.fetch_token(code=auth_code)
credentials = flow.credentials
print(credentials.__dict__)

Solution

  • The problem seemed to be that I have already completed these steps before.

    The solution was to include approval_prompt='force' in flow.authorization_url(). After generating the authorization_url this way, the response included a refresh token as well.