Skip to content

API access using own credentials (installed application flow)

msaniscalchi edited this page Sep 18, 2018 · 8 revisions

This guide will walk you through how to setup OAuth2 for API access using your own credentials using installed 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 - Creating OAuth2 credentials

Follow the steps for the product you're using to generate a client ID and secret, then come back to this page.

Step 2 - Setting up the client library

  1. In a terminal, navigate to the generate_refresh_token.py example for your product. The samples linked below are for Python 2.7.9+. You can find equivalent samples for Python 3.4.3+ on the Releases page.

  2. Run this example via the command line.

    You can either run this example with your client ID and secret provided as command-line arguments or edit the DEFAULT_CLIENT_ID and DEFAULT_CLIENT_SECRET to match them. If you provide them as command-line arguments, it would look similar to the following:

    $ python generate_refresh_token.py --client_id INSERT_CLIENT_ID --client_secret INSERT_CLIENT_SECRET
    
  3. The example will prompt you to visit a URL where you will need to allow the OAuth2 credentials to access the API on your behalf. Navigate to the URL in a private browser session or an incognito window. Log in with the same Google account you use to access Google Ads or Ad Manager, and then click Allow on the OAuth2 consent screen.

    Consent screen allow

  4. An authorization code will be shown to you. Copy and paste it into the command line where you're running the generate_refresh_token.py example and press enter. The example should complete and display an offline refresh token.

    Authorization code

    After approving the token enter the verification code (if specified).
    Code: ****
    
    Access token: ****
    Refresh token: ****
    
  5. Depending on whether you intend to use the credentials for AdWords or Ad Manager, insert your client ID, client secret, and refresh token in either the adwords or dfp section of your googleads.yaml file.

    For example, if you were configuring AdWords, it would look something like this:

    adwords:
      # ... omitted ...
      client_id: INSERT_OAUTH2_CLIENT_ID_HERE
      client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE
      refresh_token: INSERT_REFRESH_TOKEN_HERE
      # ... omitted ...
    
  6. You can now initialize either an AdWordsClient or AdManagerClient using the credentials stored in googleads.yaml. To do so, all you need to do is initialize either with their LoadFromStorage class method.

    For example, if you need to set up an AdWordsClient, the necessary code would look something like the following:

    from googleads import adwords
    
    
    # Initialize the AdWords client.
    adwords_client = adwords.AdWordsClient.LoadFromStorage()