The Google Analytics Management API allows for programmatic management of user permissions. This is especially useful for large companies with frequent updates to their access control lists (ACLs).
Introduction
There are three main resources that are used to control who can access an account, property or view (profile):
There is also special batching support for user permissions write operations.
User Permissions
A user, represented by a Google Account, can be granted the following levels of access to a Google Analytics account, property or view (profile):
MANAGE_USERS
- Needed to make write requests to the user permissions APIs.EDIT
- Needed to edit data management resources.COLLABORATE
READ_AND_ANALYZE
For additional details on each level of access see the User Permissions help center article.
Assigning permissions
The API exposes two types of permissions: local
and effective
. Local permissions apply to the given account, property or view (profile). When assigning permissions with the API you should use the permissions.local
property. Effective
permissions represent permissions that are inherited from parent resources.
Inherited permissions
If a user is granted EDIT
permission on an account, all profiles and properties under that account will inherit this permissions; this will be represented by the permissions.effective property.
Use cases
User permissions in the Management API can be used to solve the following use cases:
- List all users for an account
- Update a large number of users
- Delete a user from the account hierarchy
- Update a single user
- Add a single user
List all users for an account
To list all users for an account, including all users who have permissions on any property or view (profile) in the account, execute the list
method of the accountUserLinks resource.
Update a large number of users
To update permissions for a large number of users it is highly recommended you use batching; this will not only save quota but will also be much more performant -- see the batching section below for complete details. The steps required to carry this out for an account are:
- Get all user links for the account:
list
allaccountUserLinks
.
- Construct update requests for each user with the appropriate permissions:
update
for everyaccountUserLink
.
- Construct a single batch request for every 300 users containing the above update requests:
- call
batch
for every 300 users.
- call
Delete a user from the account hierarchy
To remove all occurrences of a user from the account hierarchy (i.e. account, properties, and views (profiles)). The steps required to carry this out are:
- Get all user links for each entity level. Execute 3
list
requests for the account: - Find and delete users with local permissions. For each response received from the 3 list operations in step 1, iterate through each
entityUserLink
:- if the
userRef
properties match the user and if thelocal
permissions are set then execute adelete
on the resource
- if the
See the API Reference for details on the delete
method of Account User Links, Web Property User Links, and View (Profile) User Links resources.
Update a single user
User permissions can also be updated using the Management API. For example, the steps to change a user's permissions level from READ_AND_ANALYZE
to EDIT
, assuming you don't know the view (profile) name or ID, are:
Get all user links for each entity level Execute 3
list
requests for the account:Find and update users with local permissions. For each response received from the 3 list operations in step #1, iterate through each
entityUserLink
:- If the
userRef
properties match the user and if the user haslocal
permissions withREAD_AND_ANALYZE
access then execute anupdate
on the resource.
- If the
See the API Reference for details on the update
method of Account User Links, Web Property User Links, and View (Profile) User Links resources.
Add a single user
To add a user to the account hierarchy, for example to a view (profile), requires the following steps:
- Use the Management API or Web Interface to retrieve IDs for the account, property, and view (profile).
- Add the user by executing the
insert
method of theprofileUserLinks
resource.
Batching
There are performance gains and quota incentives when batching permission API write (delete, insert, update) requests.
- Batched user permissions requests can take advantage of back end optimizations, and see significant performance gains.
- Every 30 batched user permission API requests counts as only a single write operation.
- Up to 300 user permissions API requests can be made in a single batch request, allowing for a higher per-user-limit QPS.
In order to get the most out of these performance gains there are certain things you should do.
- Group your API request by user.
- Only batch requests for one account. Batched user permissions requests with more than one Google Analytics account will result in an error with the following message:
All batched requests must be under the same account
.
Error Handling
All permissions calls in a batch request are treated as a single transaction. This means that if any of the mutations is in error, no changes are made. The reasons we treat them as a single call are:
- Multiple edits may be needed to adjust a single user's permissions. If one of the edits is malformed, committing part of the batch could cause the user's permissions to end up in an undesirable state.
- By treating the edits as a single transaction, we optimize the traffic and can reduce the quota required for the call.
Batching example - Python
Below is a simple example in Python of how to batch requests to add a list of users to a set of views (profiles). The example loops through the accounts for the authorized user, and for each account creates a single batch request. Within each batch requests it groups all the changes for a given user.
"""A simple example of Google Analytics batched user permissions.""" import json from googleapiclient.errors import HttpError from googleapiclient.http import BatchHttpRequest def call_back(request_id, response, exception): """Handle batched request responses.""" print request_id if exception is not None: if isinstance(exception, HttpError): message = json.loads(exception.content)['error']['message'] print ('Request %s returned API error : %s : %s ' % (request_id, exception.resp.status, message)) else: print response def add_users(users, permissions): """Adds users to every view (profile) with the given permissions. Args: users: A list of user email addresses. permissions: A list of user permissions. Note: this code assumes you have MANAGE_USERS level permissions to each profile and an authorized Google Analytics service object. """ # Get the a full set of account summaries. account_summaries = analytics.management().accountSummaries().list().execute() # Loop through each account. for account in account_summaries.get('items', []): account_id = account.get('id') # Loop through each user. for user in users: # Create the BatchHttpRequest object. batch = BatchHttpRequest(callback=call_back) # Loop through each property. for property_summary in account.get('webProperties', []): property_id = property_summary.get('id') # Loop through each view (profile). for view in property_summary.get('profiles', []): view_id = view.get('id') # Construct the Profile User Link. link = analytics.management().profileUserLinks().insert( accountId=account_id, webPropertyId=property_id, profileId=view_id, body={ 'permissions': { 'local': permissions }, 'userRef': { 'email': user } } ) batch.add(link) # Execute the batch request for each user. batch.execute() if __name__ == '__main__': # Construct a list of users. emails = ['ona@gmail.com', 'emi@gmail.com', 'sue@gmail.com', 'liz@gmail.com'] # call the add_users function with the list of desired permissions. add_users(emails, ['READ_AND_ANALYZE'])
Next steps
Next we will examine how to use the Google Analytics Management API to configure various data resources.