How To Access Google Analytics API Via Python

How To Access Google Analytics API Via Python
Image: Google API Analytics

To access the Google Analytics API via Python, you'll need to start by setting up a new project in the Google API Console. Here are the steps you'll need to follow:

  1. Go to the Google API Console.
  2. Click the project drop-down and select or create the project that you want to use for the API.
  3. Click the hamburger menu and select APIs & Services > Library.
  4. Search for "Analytics API" and click on the result.
  5. Click the Enable button.

Once you've enabled the API, you'll need to create credentials for your application. To do this:

  1. Click the hamburger menu and select APIs & Services > Credentials.
  2. Click the Create credentials button and select OAuth client ID.
  3. Select Other as the application type, and give your application a name.
  4. Click the Create button.

You should now see a new OAuth client ID in the list of credentials. To use the API, you'll need to download the Google API client library for Python, which you can do using pip.

To install the library, open a terminal and run the following command:


pip install google-api-python-client

Once you have the library installed, you can use the following code to authenticate and access the API:


from google.oauth2.credentials import Credentials # Replace with your own client_id and client_secret creds = Credentials.from_client_info({ "client_id": "YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET" }) service = build('analytics', 'v3', credentials=creds) # Use the service to send a request to the API response = service.data().ga().get( ids='ga:YOUR_VIEW_ID', start_date='30daysAgo', end_date='today', metrics='ga:sessions' ).execute() print(response)

Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with the client ID and secret that you obtained from the API Console, and replace YOUR_VIEW_ID with the ID of the view you want to access data for.

I hope this helps! Let me know if you have any questions.

Related article

0 Comments