This guide walks you through how to set up OAuth2 for API access using your own credentials in the web application flow. These steps only need to be done once, unless you revoke, delete, or need to change the allowed scopes for your OAuth2 credentials.
Step 1 - Create OAuth2 credentials
First, generate a client ID and secret by following these
instructions. If you're using the
authenticate_in_web_application
example, you'll also need to add http://localhost:8080
to the list of
authorized redirect URIs when creating your new credentials.
Once finished, save your client ID and client secret by going back to the
credentials page and
clicking the button on the right-hand side of the screen to download your
credentials as a JSON file. Save that file on your machine in a location that's
easy to remember, such as in your $HOME
directory.
Step 2 - Add OAuth2 credentials to configuration
Set the client ID and client secret tokens in your configuration. If you're
using a google-ads.yaml
file, YAML string, or dict
, add the following:
client_id: OAUTH2_CLIENT_ID
client_secret: OAUTH2_CLIENT_SECRET
If you're using environment variables, add the following to your shell configuration or environment:
export GOOGLE_ADS_CLIENT_ID=OAUTH2_CLIENT_ID
export GOOGLE_ADS_CLIENT_SECRET=OAUTH2_CLIENT_SECRET
Step 3 - Generate a refresh token
Follow the instructions in our installation documentation to clone the library from GitHub, then return to these instructions.
Next, navigate to the
authenticate_in_web_application
example,authenticate_in_web_application.py
.$ cd examples/authentication
Run this example using the command line, passing in the file path to the JSON file generated earlier.
$ ./authenticate_in_web_application.py --client_secrets_path=/path/to/secrets.json
The example then prompts you to visit a URL where you need to allow the OAuth2 credentials to access your Google Ads account on your behalf.
- Navigate to the URL in a private browser session or an incognito window.
- Sign in with the same Google account you use to access Google Ads.
- Click Allow on the OAuth2 consent screen.
After printing the above URL to the console, the example opens a socket to receive an HTTP request from the Google Auth servers, which contains an authorization code. It then parses that code and uses it to generate a refresh token that is printed to the console.
Step 4 - Add refresh token to configuration
Set the refresh token in your configuration. If you're using a google-ads.yaml
file, YAML string, or dict
, add the following:
refresh_token: OAUTH2_REFRESH_TOKEN
If you're using environment variables, add the following to your shell configuration or environment:
export GOOGLE_ADS_REFRESH_TOKEN=OAUTH2_REFRESH_TOKEN