-
Notifications
You must be signed in to change notification settings - Fork 975
API access on behalf of your clients (web flow)
API access on behalf of your clients (web flow)
This guide will walk you through how to setup OAuth2 for API access on behalf of your clients using web flow.
Follow the steps for the product you're using to generate a client ID and secret, then come back to this page.
-
Setup the OAuth2 web flow.
Using the client ID and secret you generated earlier, you can now initialize the
OAuth2WebServerFlow
instance that you can use to step through the web flow. If you were setting this up for use with AdWords, it would look like the following:from googleads import oauth2 from oauth2client import client # Initialize the flow using the client ID and secret produced earlier. # Note: You can use the GetAPIScope helper function to retrieve the # appropriate scope for AdWords or DFP. flow = client.OAuth2WebServerFlow( client_id=client_id, client_secret=client_secret, scope=oauth2.GetApiScope('adwords'), user_agent='Test', redirect_uri=redirect_uri)
Alternatively, see the OAuth2 Web App Guide for details on initializing the flow from a client_secrets.json file.
-
Retrieve the url for Google's OAuth2 server and redirect the user there.
You can retrieve the url with the following line of code:
auth_uri = flow.step1_get_authorize_url()
On redirecting the client there, it will display a prompt requesting that they allow you to access their AdWords or DFP account on their behalf.
Either selection will redirect them back to the
redirect_uri
specified earlier. -
Handle the OAuth2 server response.
If the client opted to allow you to access their account, you will receive an authorization code in the response as a query string. This can be used to retrieve an access and refresh token with the following line of code:
credentials = flow.step2_exchange(auth_code)
-
Store the user's credentials in your database so you can retrieve it the next time they login to your system.
-
You can now initialize either an
AdWordsClient
orDfpClient
using the client's stored credentials. To do so, you should provide an initializedGoogleRefreshTokenClient
to the AdWords/DFP client via theoauth2_client
argument during initialization.For example, if you need to set up an AdWordsClient, it may look something like the following:
from googleads import adwords from googleads import oauth2 # Initialize the GoogleRefreshTokenClient using the credentials you received # in the earlier steps. oauth2_client = oauth2.GoogleRefreshTokenClient( client_id, client_secret, refresh_token) # Initialize the AdWords client. adwords_client = adwords.AdWordsClient( developer_token, oauth2_client, user_agent, client_customer_id)