En el siguiente ejemplo, se muestra una función auxiliar para crear un dispositivo mediante la biblioteca HTTP de Python:
"""Example script to use the create method of 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=''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')ifnotSA_FILEornotADMIN_EMAIL: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')################################ Create the Deviceheader={'authorization':'Bearer '+dc.token,'Content-Type':'application/json'}body={'serialNumber':'someSerial',# the serial number of your device.# see values in# https://cloud.google.com/identity/docs/reference/rest/v1/devices#DeviceType'deviceType':'LINUX'}serialized_body=json.dumps(body,separators=(',',':'))request_url=BASE_URL+'devices'print('Request URL: '+request_url)print('Request body: '+serialized_body)serialized_body=json.dumps(body,separators=(',',':'))request=urllib.request.Request(request_url,serialized_body,headers=header)request.get_method=lambda:'POST'try:contents=urllib.request.urlopen(request)excepturllib.error.HTTPErrorase:ife.code==409:print('The request was invalid. Perhaps the device is already present?')else:print('Unknown error occurred: {}',e.code)exit(-1)create_response=json.loads(contents.read())inner_response=create_response['response']pp=pprint.PrettyPrinter(indent=4)pp.pprint(inner_response)
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-04 (UTC)"],[[["\u003cp\u003eBefore using the Cloud Identity APIs, you must set up Cloud Identity as detailed in the setup instructions.\u003c/p\u003e\n"],["\u003cp\u003ePrior to creating a device, it is recommended to read the Devices API overview and set up the Devices API.\u003c/p\u003e\n"],["\u003cp\u003eTo create a device via REST, utilize the \u003ccode\u003edevices.create()\u003c/code\u003e method, specifying the customer name and a Device object.\u003c/p\u003e\n"],["\u003cp\u003ePython HTTP library users can employ a helper function, as demonstrated in the provided example, to create devices, which includes defining credentials, authentication, and device specifications.\u003c/p\u003e\n"],["\u003cp\u003eThe provided Python script gives an example on how to create a device by authenticating a service account and then sending a POST request to the API.\u003c/p\u003e\n"]]],[],null,["# Creating devices\n================\n\nThis page explains how to create devices.\n\nBefore you begin\n----------------\n\n| **Note:** Before you use any of the Cloud Identity APIs, you must set up Cloud Identity. See [Setting up Cloud Identity](/identity/docs/set-up-cloud-identity-admin) for instructions.\n\nPerform the following tasks before proceeding with the information on this page:\n\n- Read the [Devices API overview](/identity/docs/concepts/overview-devices).\n\n- [Set up the Devices API](/identity/docs/how-to/setup).\n\nCreating a device\n-----------------\n\nThe following examples shows you how to create a device. \n\n### REST\n\nTo create a device, call\n[`devices.create()`](/identity/docs/reference/rest/v1beta1/devices/create)\nwith the name of the `customer` (organization) and a\n[Device object](/identity/docs/reference/rest/v1/devices).\n\n### Python HTTP\n\nThe following example shows a helper function to create a device\nusing the Python HTTP library: \n\n \"\"\"Example script to use the create method of 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 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\n if not SA_FILE or not ADMIN_EMAIL:\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 # Create the Device\n header = {\n 'authorization': 'Bearer ' + dc.token,\n 'Content-Type': 'application/json'\n }\n body = {\n 'serialNumber': 'someSerial', # the serial number of your device.\n\n # see values in\n # https://cloud.google.com/identity/docs/reference/rest/v1/devices#DeviceType\n 'deviceType': 'LINUX'\n }\n\n serialized_body = json.dumps(body, separators=(',', ':'))\n\n request_url = BASE_URL + 'devices'\n print('Request URL: ' + request_url)\n print('Request body: ' + serialized_body)\n\n serialized_body = json.dumps(body, separators=(',', ':'))\n request = urllib.request.Request(request_url, serialized_body, headers=header)\n request.get_method = lambda: 'POST'\n\n try:\n contents = urllib.request.urlopen(request)\n except urllib.error.HTTPError as e:\n if e.code == 409:\n print('The request was invalid. Perhaps the device is already present?')\n else:\n print('Unknown error occurred: {}', e.code)\n exit(-1)\n\n create_response = json.loads(contents.read())\n inner_response = create_response['response']\n pp = pprint.PrettyPrinter(indent=4)\n pp.pprint(inner_response)"]]