Skip to content

API access using own credentials (installed application flow)

msaniscalchi edited this page Dec 9, 2022 · 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.

  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 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. Insert your client ID, client secret, and refresh token in the ad_manager section of your googleads.yaml file.

    ad_manager:
      # ... 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 an AdManagerClient using the credentials stored in googleads.yaml. To do so, all you need to do is initialize either with the LoadFromStorage class method.

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

    from googleads import ad_manager
    
    
    # Initialize the Ad Manager client.
    ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()