The following example shows a helper function to update the client state
using the Python HTTP library:
"""Sample script to demonstrate the use of the Update method in the Devices API."""importjsonimportpprintfromsix.movesimporturllibimportgoogle.auth.transport.requestsfromgoogle.oauth2importservice_accountSCOPES=['https://www.googleapis.com/auth/cloud-identity.devices']BASE_URL='https://cloudidentity.googleapis.com/v1/'# Change this to the location of the service account keySA_FILE=''# Enter the administrator to call as here.ADMIN_EMAIL=''# Enter the Device User Resource Name. You can get this from the value# of the name field in the results of a List method callRESOURCE_NAME=''# Enter the Client ID, which is in the format <customer-id>-<somestring># Where 'customer-id' is your customer id.CLIENT_ID=''ifnotSA_FILE:print('Please specify the location of the service account key file')ifnotADMIN_EMAIL:print('Please specify the email of the administrator to call as')ifnotRESOURCE_NAME:print('Please specify the Device User Resource Name to be approved')ifnotCLIENT_ID:print('Please specify your client id, which is your customer-id, followed by'' a hyphen, folowed by any string')ifnotSA_FILEornotADMIN_EMAILornotRESOURCE_NAMEornotCLIENT_ID:exit(-1)defcreate_delegated_credentials(user_email):credentials=service_account.Credentials.from_service_account_file(SA_FILE,scopes=['https://www.googleapis.com/auth/cloud-identity.devices'])delegated_credentials=credentials.with_subject(user_email)returndelegated_credentials####################################################################### AUTHENTICATE the service account and retrieve an oauth2 access tokenrequest=google.auth.transport.requests.Request()dc=create_delegated_credentials(ADMIN_EMAIL)dc.refresh(request)print('Access token: '+dc.token+'\n')################################ Update the client stateheader={'authorization':'Bearer '+dc.token,'Content-Type':'application/json'}body={'customId':'abcd','assetTags':['efgh','ijkl'],'healthScore':'GOOD','scoreReason':'all ok','managed':'MANAGED','complianceState':'COMPLIANT'}update_clientstate_url=BASE_URL+RESOURCE_NAME+'/clientStates/'+CLIENT_ID+'?updateMask='+'customId,assetTags,healthScore,scoreReason,managed,complianceState'serialized_body=json.dumps(body,separators=(',',':'))request=urllib.request.Request(update_clientstate_url,serialized_body,headers=header)request.get_method=lambda:'PATCH'try:contents=urllib.request.urlopen(request)excepturllib.error.HTTPErrorase:ife.code==404:print('The resource was not found')else:print('Permission denied. Did you provide the correct client id?')exit(-1)update_response=json.loads(contents.read())pp=pprint.PrettyPrinter(indent=4)pp.pprint(update_response['response'])
[[["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-09-03 UTC."],[[["\u003cp\u003eThe client state for the Devices API can be updated using the \u003ccode\u003edevices.clientStates.patch()\u003c/code\u003e REST API method, which requires a customer name and a ClientState object.\u003c/p\u003e\n"],["\u003cp\u003eA Python HTTP example is provided demonstrating how to update the client state, including setting up service account authentication and defining the necessary parameters.\u003c/p\u003e\n"],["\u003cp\u003eUpdating the client state requires specifying parameters such as \u003ccode\u003ecustomId\u003c/code\u003e, \u003ccode\u003eassetTags\u003c/code\u003e, \u003ccode\u003ehealthScore\u003c/code\u003e, \u003ccode\u003escoreReason\u003c/code\u003e, \u003ccode\u003emanaged\u003c/code\u003e, and \u003ccode\u003ecomplianceState\u003c/code\u003e in the request body.\u003c/p\u003e\n"],["\u003cp\u003eThe update operation uses a PATCH request to a specific URL constructed from the base URL, resource name, client ID, and an update mask specifying the fields to modify.\u003c/p\u003e\n"],["\u003cp\u003eThe provided example script checks for required information before proceeding, then authenticates, updates the specified client state, and handles potential HTTP errors like a 404 (resource not found).\u003c/p\u003e\n"]]],[],null,["# Updating the client state\n=========================\n\nThe following examples shows you how to update the client state for the API\nclient calling the Devices API. \n\n### REST\n\nTo update the client state, call\n[`devices.clientStates.patch()`](/identity/docs/reference/rest/v1/devices.deviceUsers.clientStates/patch)\nwith a customer name and\n[ClientState](/identity/docs/reference/rest/v1/devices.deviceUsers.clientStates#ClientState) object.\n\n### Python HTTP\n\nThe following example shows a helper function to update the client state\nusing the Python HTTP library: \n\n \"\"\"Sample script to demonstrate the use of the Update method in the Devices API.\"\"\"\n import json\n import pprint\n\n from six.moves import urllib\n\n import google.auth.transport.requests\n from google.oauth2 import service_account\n\n SCOPES = ['https://www.googleapis.com/auth/cloud-identity.devices']\n BASE_URL = 'https://cloudidentity.googleapis.com/v1/'\n\n # Change this to the location of the service account key\n SA_FILE = ''\n\n # Enter the administrator to call as here.\n ADMIN_EMAIL = ''\n\n # Enter the Device User Resource Name. You can get this from the value\n # of the name field in the results of a List method call\n RESOURCE_NAME = ''\n\n # Enter the Client ID, which is in the format \u003ccustomer-id\u003e-\u003csomestring\u003e\n # Where 'customer-id' is your customer id.\n CLIENT_ID = ''\n\n if not SA_FILE:\n print('Please specify the location of the service account key file')\n if not ADMIN_EMAIL:\n print('Please specify the email of the administrator to call as')\n if not RESOURCE_NAME:\n print('Please specify the Device User Resource Name to be approved')\n if not CLIENT_ID:\n print('Please specify your client id, which is your customer-id, followed by'\n ' a hyphen, folowed by any string')\n\n if not SA_FILE or not ADMIN_EMAIL or not RESOURCE_NAME or not CLIENT_ID:\n exit(-1)\n\n def create_delegated_credentials(user_email):\n credentials = service_account.Credentials.from_service_account_file(\n SA_FILE,\n scopes=['https://www.googleapis.com/auth/cloud-identity.devices'])\n\n delegated_credentials = credentials.with_subject(user_email)\n\n return delegated_credentials\n\n ######################################################################\n # AUTHENTICATE the service account and retrieve an oauth2 access token\n\n request = google.auth.transport.requests.Request()\n dc = create_delegated_credentials(ADMIN_EMAIL)\n dc.refresh(request)\n print('Access token: ' + dc.token + '\\n')\n\n ###############################\n # Update the client state\n header = {\n 'authorization': 'Bearer ' + dc.token,\n 'Content-Type': 'application/json'\n }\n body = {\n 'customId': 'abcd',\n 'assetTags': ['efgh', 'ijkl'],\n 'healthScore': 'GOOD',\n 'scoreReason': 'all ok',\n 'managed': 'MANAGED',\n 'complianceState': 'COMPLIANT'\n }\n\n update_clientstate_url = BASE_URL + RESOURCE_NAME + '/clientStates/' + CLIENT_ID + '?updateMask=' +\n 'customId,assetTags,healthScore,scoreReason,managed,complianceState'\n\n serialized_body = json.dumps(body, separators=(',', ':'))\n request = urllib.request.Request(\n update_clientstate_url, serialized_body, headers=header)\n request.get_method = lambda: 'PATCH'\n\n try:\n contents = urllib.request.urlopen(request)\n except urllib.error.HTTPError as e:\n if e.code == 404:\n print('The resource was not found')\n else:\n print('Permission denied. Did you provide the correct client id?')\n exit(-1)\n\n update_response = json.loads(contents.read())\n pp = pprint.PrettyPrinter(indent=4)\n pp.pprint(update_response['response'])"]]