![]() |
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:
- Go to the Google API Console.
- Click the project drop-down and select or create the project that you want to use for the API.
- Click the hamburger menu and select APIs & Services > Library.
- Search for "Analytics API" and click on the result.
- Click the Enable button.
Once you've enabled the API, you'll need to create credentials for your application. To do this:
- Click the hamburger menu and select APIs & Services > Credentials.
- Click the Create credentials button and select OAuth client ID.
- Select Other as the application type, and give your application a name.
- 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.