The following example shows you how to list policies in your organization using
Python.
"""Sample script to demonstrate the use of the List method in the Policy API."""fromcollections.abcimportMapping,SequenceimportjsonimportpprintimporttimefromtypingimportAnyimporturllib.requestfromabslimportappfromabslimportflagsimportgoogle.auth.transport.requestsfromgoogle.oauth2importservice_accountSCOPES=['https://www.googleapis.com/auth/cloud-identity.policies']BASE_URL='https://cloudidentity.googleapis.com/'VERSIONED_BASE_URL=f'{BASE_URL}v1/'_SA_FILE=flags.DEFINE_string(name='sa_file',default=None,help='Service account credentials file path',required=True,)_ADMIN_EMAIL=flags.DEFINE_string(name='admin_email',default=None,help='Administrator email to call as',required=True,)_PAGE_SIZE=flags.DEFINE_integer(name='page_size',default=50,help='Page size for the List API request',required=False,)# To list all policies, set FILTER to '';# To list policies for a specific customer, set FILTER to# 'customer == "customers/{obfuscated_target_customer_id}"';# To list policies for a specific Application, such as Gmail, set FILTER to# 'setting.type.matches("gmail.*")';# To list policies for a specific Setting, such as service_status, set FILTER to# 'setting.type.matches(".*service_status")'._LIST_FILTER=flags.DEFINE_string(name='list_filter',default='',help='Filter for the List API request',required=False,)defcreate_delegated_credentials(sa_file:str,user_email:str)-> service_account.Credentials:"""Creates delegated credentials for the user. Args: sa_file: The service account credentials file path. user_email: The administrator email to call as. Returns: The delegated credentials for the user. """credentials=service_account.Credentials.from_service_account_file(sa_file,scopes=SCOPES)delegated_credentials=credentials.with_subject(user_email)returndelegated_credentialsdefbuild_list_policies_request(page_size:int,list_filter:str,page_token:str,access_token:str)-> urllib.request.Request:"""Builds the request for the List Policies API. Args: page_size: The page size for the request. list_filter: The filter for the request. page_token: The page token for the request. access_token: The access token for the API. Returns: The request for the List Policies API. """list_url=(f'{VERSIONED_BASE_URL}policies?page_size={page_size}'f'&filter={list_filter}&page_token={page_token}')request=urllib.request.Request(list_url)request.add_header('Authorization','Bearer '+access_token)returnrequestdefcall_list_policies_api(request:urllib.request.Request,)-> Mapping[str,Any]:"""Calls the List Policies API. Args: request: The request for the List Policies API. Returns: The response for the List Policies API. """content=urllib.request.urlopen(request).read()returnjson.loads(content)defcall_list_policies_api_till_last_page(access_token:str,page_size:int,list_filter:str)-> None:"""Calls the List Policies API until the last page. Args: access_token: The access token for the API. page_size: The page size for the request. list_filter: The filter for the request. """page_token=''# Paginate until the last page.whileTrue:list_policies_request=build_list_policies_request(page_size,list_filter,page_token,access_token)list_policies_response=call_list_policies_api(list_policies_request)print_list_policies_response(list_policies_response)if('nextPageToken'notinlist_policies_responseornotlist_policies_response['nextPageToken']):print('This is the last page.')breakpage_token=list_policies_response['nextPageToken']time.sleep(1)defprint_list_policies_response(response:Mapping[str,Any])-> None:pp=pprint.PrettyPrinter(indent=4)if'policies'inresponse:forpolicyinresponse['policies']:pp.pprint(policy)if'nextPageToken'inresponse:print('Next page token: '+response['nextPageToken'])defmain(argv:Sequence[str]):iflen(argv) > 4:raiseapp.UsageError('Too many command-line arguments.')dc=create_delegated_credentials(_SA_FILE.value,_ADMIN_EMAIL.value)dc.refresh(google.auth.transport.requests.Request())call_list_policies_api_till_last_page(dc.token,_PAGE_SIZE.value,_LIST_FILTER.value,)if__name__=='__main__':app.run(main)
Get policy
The following example show you how to retrieve a specific policy using Python.
"""Sample script to demonstrate the use of the get method in the Policy API."""fromcollections.abcimportSequenceimportjsonimportpprintimporturllib.requestfromabslimportappfromabslimportflagsimportgoogle.auth.transport.requestsfromgoogle.oauth2importservice_accountSCOPES=['https://www.googleapis.com/auth/cloud-identity.policies']BASE_URL='https://cloudidentity.googleapis.com/'VERSIONED_BASE_URL=f'{BASE_URL}v1/'_SA_FILE=flags.DEFINE_string(name='sa_file',default=None,help='Service account credentials file path',required=True,)_ADMIN_EMAIL=flags.DEFINE_string(name='admin_email',default=None,help='Administrator email to call as',required=True,)_POLICY_NAME=flags.DEFINE_string(name='policy_name',default=None,help='Policy name of the policy to get',required=True,)defcreate_delegated_credentials(sa_file:str,user_email:str)-> service_account.Credentials:"""Creates delegated credentials for the user. Args: sa_file: The service account credentials file path. user_email: The administrator email to call as. Returns: The delegated credentials for the user. """credentials=service_account.Credentials.from_service_account_file(sa_file,scopes=SCOPES)delegated_credentials=credentials.with_subject(user_email)returndelegated_credentialsdefbuild_get_policy_request(policy_name:str,access_token:str)-> urllib.request.Request:"""Builds the request for the Get Policy API. Args: policy_name: The policy name to get. access_token: The access token for the API. Returns: The request for the Get Policy API. """list_url=f'{VERSIONED_BASE_URL}{policy_name}'request=urllib.request.Request(list_url)request.add_header('Authorization','Bearer '+access_token)returnrequestdefcall_get_policy_api(access_token:str,policy_name:str)-> None:"""Calls the Get Policy API. Args: access_token: The access token for the API. policy_name: The policy name to get. """request=build_get_policy_request(policy_name,access_token)content=urllib.request.urlopen(request).read()response=json.loads(content)print_get_policy_response(response)defprint_get_policy_response(response:str)-> None:pp=pprint.PrettyPrinter(indent=4)pp.pprint(response)defmain(argv:Sequence[str]):iflen(argv) > 3:raiseapp.UsageError('Too many command-line arguments.')dc=create_delegated_credentials(_SA_FILE.value,_ADMIN_EMAIL.value)dc.refresh(google.auth.transport.requests.Request())call_get_policy_api(dc.token,_POLICY_NAME.value)if__name__=='__main__':app.run(main)
Quota
For each Google Cloud project, Cloud Identity Policy API supports 1 query per
second (QPS). For each customer, Cloud Identity Policy API supports 1 QPS in total,
even if the customer creates multiple Google Cloud projects.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-29 UTC."],[[["\u003cp\u003eThis page provides Python code examples for interacting with the Cloud Identity Policy API to list and retrieve policies.\u003c/p\u003e\n"],["\u003cp\u003eBefore using the provided examples, you must first complete the setup process for the Policy API as detailed in the "Setting up the Policy API" documentation.\u003c/p\u003e\n"],["\u003cp\u003eThe provided \u003ccode\u003elist policies\u003c/code\u003e example demonstrates how to filter and paginate through policies using various criteria, such as customer, application, or setting.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eget policy\u003c/code\u003e example demonstrates how to use the API to retrieve a specific policy by its unique policy name.\u003c/p\u003e\n"],["\u003cp\u003eThe Cloud Identity Policy API is subject to a quota of 1 query per second (QPS) per Google Cloud project and per customer, with quota increases not being supported.\u003c/p\u003e\n"]]],[],null,["# Listing and getting policies\n============================\n\nThis page provides code examples that demonstrate how to list and get policies.\n\nBefore you begin\n----------------\n\nComplete the [Setting up the Policy API](/identity/docs/how-to/setup-policies).\n\nList policies\n-------------\n\nThe following example shows you how to list policies in your organization using\nPython. \n\n \"\"\"Sample script to demonstrate the use of the List method in the Policy API.\"\"\"\n\n from collections.abc import Mapping, Sequence\n import json\n import pprint\n import time\n from typing import Any\n import urllib.request\n from absl import app\n from absl import flags\n import google.auth.transport.requests\n from google.oauth2 import service_account\n\n SCOPES = ['https://www.googleapis.com/auth/cloud-identity.policies']\n BASE_URL = 'https://cloudidentity.googleapis.com/'\n VERSIONED_BASE_URL = f'{BASE_URL}v1/'\n\n _SA_FILE = flags.DEFINE_string(\n name='sa_file',\n default=None,\n help='Service account credentials file path',\n required=True,\n )\n\n _ADMIN_EMAIL = flags.DEFINE_string(\n name='admin_email',\n default=None,\n help='Administrator email to call as',\n required=True,\n )\n\n _PAGE_SIZE = flags.DEFINE_integer(\n name='page_size',\n default=50,\n help='Page size for the List API request',\n required=False,\n )\n\n # To list all policies, set FILTER to '';\n # To list policies for a specific customer, set FILTER to\n # 'customer == \"customers/{obfuscated_target_customer_id}\"';\n # To list policies for a specific Application, such as Gmail, set FILTER to\n # 'setting.type.matches(\"gmail.*\")';\n # To list policies for a specific Setting, such as service_status, set FILTER to\n # 'setting.type.matches(\".*service_status\")'.\n _LIST_FILTER = flags.DEFINE_string(\n name='list_filter',\n default='',\n help='Filter for the List API request',\n required=False,\n )\n\n\n def create_delegated_credentials(\n sa_file: str, user_email: str\n ) -\u003e service_account.Credentials:\n \"\"\"Creates delegated credentials for the user.\n\n Args:\n sa_file: The service account credentials file path.\n user_email: The administrator email to call as.\n\n Returns:\n The delegated credentials for the user.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_file(\n sa_file, scopes=SCOPES\n )\n delegated_credentials = credentials.with_subject(user_email)\n return delegated_credentials\n\n\n def build_list_policies_request(\n page_size: int, list_filter: str, page_token: str, access_token: str\n ) -\u003e urllib.request.Request:\n \"\"\"Builds the request for the List Policies API.\n\n Args:\n page_size: The page size for the request.\n list_filter: The filter for the request.\n page_token: The page token for the request.\n access_token: The access token for the API.\n\n Returns:\n The request for the List Policies API.\n \"\"\"\n list_url = (\n f'{VERSIONED_BASE_URL}policies?page_size={page_size}'\n f'&filter={list_filter}&page_token={page_token}'\n )\n request = urllib.request.Request(list_url)\n request.add_header('Authorization', 'Bearer ' + access_token)\n return request\n\n\n def call_list_policies_api(\n request: urllib.request.Request,\n ) -\u003e Mapping[str, Any]:\n \"\"\"Calls the List Policies API.\n\n Args:\n request: The request for the List Policies API.\n\n Returns:\n The response for the List Policies API.\n \"\"\"\n content = urllib.request.urlopen(request).read()\n return json.loads(content)\n\n\n def call_list_policies_api_till_last_page(\n access_token: str, page_size: int, list_filter: str\n ) -\u003e None:\n \"\"\"Calls the List Policies API until the last page.\n\n Args:\n access_token: The access token for the API.\n page_size: The page size for the request.\n list_filter: The filter for the request.\n \"\"\"\n page_token = ''\n # Paginate until the last page.\n while True:\n list_policies_request = build_list_policies_request(\n page_size, list_filter, page_token, access_token\n )\n list_policies_response = call_list_policies_api(list_policies_request)\n print_list_policies_response(list_policies_response)\n if (\n 'nextPageToken' not in list_policies_response\n or not list_policies_response['nextPageToken']\n ):\n print('This is the last page.')\n break\n page_token = list_policies_response['nextPageToken']\n time.sleep(1)\n\n\n def print_list_policies_response(response: Mapping[str, Any]) -\u003e None:\n pp = pprint.PrettyPrinter(indent=4)\n\n if 'policies' in response:\n for policy in response['policies']:\n pp.pprint(policy)\n if 'nextPageToken' in response:\n print('Next page token: ' + response['nextPageToken'])\n\n\n def main(argv: Sequence[str]):\n if len(argv) \u003e 4:\n raise app.UsageError('Too many command-line arguments.')\n\n dc = create_delegated_credentials(_SA_FILE.value, _ADMIN_EMAIL.value)\n dc.refresh(google.auth.transport.requests.Request())\n call_list_policies_api_till_last_page(\n dc.token,\n _PAGE_SIZE.value,\n _LIST_FILTER.value,\n )\n\n\n if __name__ == '__main__':\n app.run(main)\n\nGet policy\n----------\n\nThe following example show you how to retrieve a specific policy using Python. \n\n \"\"\"Sample script to demonstrate the use of the get method in the Policy API.\"\"\"\n\n from collections.abc import Sequence\n import json\n import pprint\n import urllib.request\n from absl import app\n from absl import flags\n import google.auth.transport.requests\n from google.oauth2 import service_account\n\n SCOPES = ['https://www.googleapis.com/auth/cloud-identity.policies']\n BASE_URL = 'https://cloudidentity.googleapis.com/'\n VERSIONED_BASE_URL = f'{BASE_URL}v1/'\n\n _SA_FILE = flags.DEFINE_string(\n name='sa_file',\n default=None,\n help='Service account credentials file path',\n required=True,\n )\n\n _ADMIN_EMAIL = flags.DEFINE_string(\n name='admin_email',\n default=None,\n help='Administrator email to call as',\n required=True,\n )\n\n _POLICY_NAME = flags.DEFINE_string(\n name='policy_name',\n default=None,\n help='Policy name of the policy to get',\n required=True,\n )\n\n\n def create_delegated_credentials(\n sa_file: str, user_email: str\n ) -\u003e service_account.Credentials:\n \"\"\"Creates delegated credentials for the user.\n\n Args:\n sa_file: The service account credentials file path.\n user_email: The administrator email to call as.\n\n Returns:\n The delegated credentials for the user.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_file(\n sa_file, scopes=SCOPES\n )\n delegated_credentials = credentials.with_subject(user_email)\n return delegated_credentials\n\n\n def build_get_policy_request(\n policy_name: str, access_token: str\n ) -\u003e urllib.request.Request:\n \"\"\"Builds the request for the Get Policy API.\n\n Args:\n policy_name: The policy name to get.\n access_token: The access token for the API.\n\n Returns:\n The request for the Get Policy API.\n \"\"\"\n list_url = f'{VERSIONED_BASE_URL}{policy_name}'\n request = urllib.request.Request(list_url)\n request.add_header('Authorization', 'Bearer ' + access_token)\n return request\n\n\n def call_get_policy_api(access_token: str, policy_name: str) -\u003e None:\n \"\"\"Calls the Get Policy API.\n\n Args:\n access_token: The access token for the API.\n policy_name: The policy name to get.\n \"\"\"\n request = build_get_policy_request(policy_name, access_token)\n content = urllib.request.urlopen(request).read()\n response = json.loads(content)\n print_get_policy_response(response)\n\n\n def print_get_policy_response(response: str) -\u003e None:\n pp = pprint.PrettyPrinter(indent=4)\n pp.pprint(response)\n\n\n def main(argv: Sequence[str]):\n if len(argv) \u003e 3:\n raise app.UsageError('Too many command-line arguments.')\n\n dc = create_delegated_credentials(_SA_FILE.value, _ADMIN_EMAIL.value)\n dc.refresh(google.auth.transport.requests.Request())\n call_get_policy_api(dc.token, _POLICY_NAME.value)\n\n\n if __name__ == '__main__':\n app.run(main)\n\nQuota\n-----\n\nFor each Google Cloud project, Cloud Identity Policy API supports 1 query per\nsecond (QPS). For each customer, Cloud Identity Policy API supports 1 QPS in total,\neven if the customer creates multiple Google Cloud projects.\n\nQuota increase is not supported."]]