Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Requisitos previos para la API de Indexing
Para poder comenzar a usar la API de Indexing, debes completar algunas acciones, si es que todavía no lo hiciste:
Crea un proyecto para tu cliente
Para poder enviar solicitudes a la API de Indexing, primero debes notificar a Google acerca de tu cliente y activar el acceso a la API. Puedes hacerlo con la Consola de APIs de Google si creas un proyecto (una colección determinada de configuraciones y datos de acceso a la API) y registras la aplicación.
Para comenzar a usar la API de Indexing, primero debes emplear la herramienta de configuración, que te guiará en el proceso de creación de un proyecto en Google API Console, la habilitación de la API y la creación de credenciales.
Crea una cuenta de servicio
- Abre la página Cuentas de servicio. Si se te solicita, selecciona un proyecto.
- Haz clic en add Crear cuenta de servicio y, luego, ingresa un nombre y una descripción para la cuenta de servicio. Puedes usar el ID predeterminado de la cuenta de servicio o elegir uno que sea único y diferente. Cuando hayas terminado, haz clic en Crear.
- No es obligatoria la sección de Permisos de cuenta de servicio (opcional) que aparece a continuación. Haz clic en Continuar.
- En la pantalla Otorga a usuarios acceso a esta cuenta de servicio, desplázate hacia abajo hasta encontrar la sección Crear clave. Haz clic en add Crear clave.
- En el panel lateral que aparece, selecciona el formato para tu clave: se recomienda el código JSON.
- Haz clic en Crear. Ya se generó y descargó el nuevo par de claves pública y privada en tu equipo, que será la única copia. Para obtener más información a fin de almacenarla de forma segura, consulta Cómo administrar claves para cuentas de servicio.
- Haz clic en Cerrar, en el diálogo Se guardó la clave privada en tu computadora, y luego haz clic en Listo para regresar a la tabla de tus cuentas de servicio.
Cómo agregar tu cuenta de servicio como propietario del sitio
Para agregar tu cuenta de servicio como propietario del sitio, haz lo siguiente:
- Primero, demuestra que eres el propietario del sitio con Search Console.
- Luego, agrega tu cuenta de servicio como propietario.
1. Demuestra que eres el propietario del sitio
Verifica la propiedad de tu sitio con Search Console.
Puedes usar cualquier método de verificación que admita Search Console. Puedes crear una Propiedad de dominio (example.com
) o una propiedad con prefijo de URL (https://example.com
o https://example.com/some/path/
) para representar tu sitio (ten en cuenta que los sitios se denominan propiedades en Search Console).
2. Otorga el estado de propietario a tu cuenta de servicio
Luego, sigue estos pasos para agregar tu cuenta de servicio como propietario (delegado) del sitio:
- Abre Search Console.
- Haz clic en la propiedad que verificaste como propia.
- En la lista Propietario verificado, haz clic en la opción para agregar un propietario.
- Proporciona el correo electrónico de la cuenta de servicio como propietario delegado. Puedes encontrarlo en dos lugares:
- El campo
client_email
de la clave privada de JSON que descargaste cuando creaste el proyecto
- La columna ID de cuenta de servicio de la vista Cuentas de servicio de la consola de Google Cloud
La dirección de correo electrónico tiene un formato como el siguiente:
my-service-account@project-name.google.com.iam.gserviceaccount.com
Por ejemplo: my-service-account@test-project-42.google.com.iam.gserviceaccount.com
Obtén un token de acceso
Cada llamada a la API de Indexing debe autenticarse con un token OAuth que obtienes a cambio de la clave privada. Los token tienen una validez temporal.
Google proporciona bibliotecas cliente de API a fin de obtener tokens OAuth para varios lenguajes.
Requisitos
Cuando envíes una solicitud a la API de Indexing, sigue estos pasos:
- Usa
https://www.googleapis.com/auth/indexing
como alcance.
- Utiliza uno de los extremos que se describen en Cómo usar la API.
- Incluye el token de acceso de la cuenta de servicio.
- Define el cuerpo de la solicitud como se describe en Cómo usar la API.
Ejemplos
En los siguientes ejemplos, se muestra el proceso para obtener un token de acceso OAuth.
Python
Obtiene un token OAuth token con la biblioteca cliente de la API de Google para Python:
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
SCOPES = [ "https://www.googleapis.com/auth/indexing" ]
ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish"
# service_account_file.json is the private key that you created for your service account.
JSON_KEY_FILE = "service_account_file.json"
credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES)
http = credentials.authorize(httplib2.Http())
# Define contents here as a JSON string.
# This example shows a simple update request.
# Other types of requests are described in the next step.
content = """{
\"url\": \"http://example.com/jobs/42\",
\"type\": \"URL_UPDATED\"
}"""
response, content = http.request(ENDPOINT, method="POST", body=content)
Java
Obtiene un token OAuth con la biblioteca cliente de la API de Google para Java:
String scopes = "https://www.googleapis.com/auth/indexing";
String endPoint = "https://indexing.googleapis.com/v3/urlNotifications:publish";
JsonFactory jsonFactory = new JacksonFactory();
// service_account_file.json is the private key that you created for your service account.
InputStream in = IOUtils.toInputStream("service_account_file.json");
GoogleCredential credentials =
GoogleCredential.fromStream(in, this.httpTransport, jsonFactory).createScoped(Collections.singleton(scopes));
GenericUrl genericUrl = new GenericUrl(endPoint);
HttpRequestFactory requestFactory = this.httpTransport.createRequestFactory();
// Define content here. The structure of the content is described in the next step.
String content = "{"
+ "\"url\": \"http://example.com/jobs/42\","
+ "\"type\": \"URL_UPDATED\","
+ "}";
HttpRequest request =
requestFactory.buildPostRequest(genericUrl, ByteArrayContent.fromString("application/json", content));
credentials.initialize(request);
HttpResponse response = request.execute();
int statusCode = response.getStatusCode();
PHP
Obtiene un token OAuth con la biblioteca cliente de la API de Google para PHP:
require_once 'google-api-php-client/vendor/autoload.php';
$client = new Google_Client();
// service_account_file.json is the private key that you created for your service account.
$client->setAuthConfig('service_account_file.json');
$client->addScope('https://www.googleapis.com/auth/indexing');
// Get a Guzzle HTTP Client
$httpClient = $client->authorize();
$endpoint = 'https://indexing.googleapis.com/v3/urlNotifications:publish';
// Define contents here. The structure of the content is described in the next step.
$content = '{
"url": "http://example.com/jobs/42",
"type": "URL_UPDATED"
}';
$response = $httpClient->post($endpoint, [ 'body' => $content ]);
$status_code = $response->getStatusCode();
Node.js
Obtiene un token OAuth con la biblioteca cliente de Node.js:
var request = require("request");
var { google } = require("googleapis");
var key = require("./service_account.json");
const jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
["https://www.googleapis.com/auth/indexing"],
null
);
jwtClient.authorize(function(err, tokens) {
if (err) {
console.log(err);
return;
}
let options = {
url: "https://indexing.googleapis.com/v3/urlNotifications:publish",
method: "POST",
// Your options, which must include the Content-Type and auth headers
headers: {
"Content-Type": "application/json"
},
auth: { "bearer": tokens.access_token },
// Define contents here. The structure of the content is described in the next step.
json: {
"url": "http://example.com/jobs/42",
"type": "URL_UPDATED"
}
};
request(options, function (error, response, body) {
// Handle the response
console.log(body);
});
});
Además de mostrar el proceso para obtener un token, estos ejemplos muestran el punto en el que puedes agregar el cuerpo del mensaje de la solicitud. Para obtener información acerca de los tipos de llamada que puedes hacer y la estructura de los cuerpos del mensaje para ellas, consulta Cómo usar la API.
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2025-08-04 (UTC)
[null,null,["Última actualización: 2025-08-04 (UTC)"],[[["\u003cp\u003eTo utilize the Indexing API, you must first create a project, a service account, and add the service account as a site owner in Search Console.\u003c/p\u003e\n"],["\u003cp\u003eAfter setup, each API call needs an OAuth token, which you get in exchange for your private key using Google's API client libraries and adhering to specific requirements.\u003c/p\u003e\n"],["\u003cp\u003eWhen making a request, you must define the request body and use the appropriate endpoint as detailed in the Indexing API documentation's "Using the API" section.\u003c/p\u003e\n"],["\u003cp\u003eGoogle provides API client libraries in multiple programming languages, such as Python, Java, PHP, and Node.js, to simplify the process of getting OAuth tokens and making API calls.\u003c/p\u003e\n"]]],["To use the Indexing API, you must first create a project in the Google API Console, create a service account with a JSON key, and then add this service account as a delegated owner of your site in Search Console. Finally, get an OAuth access token using your private key to authenticate API calls. Each request must use `https://www.googleapis.com/auth/indexing` as the scope, and include the service account access token. The content gives examples in different programming languages.\n"],null,["# Prerequisites for the Indexing API | Google Search Central\n\nPrerequisites for the Indexing API\n==================================\n\nBefore you can start using the Indexing API, there are a few\nthings you need to do, if you haven't done them already:\n\n- [Create a project for your client](#create-project)\n- [Create a service account](#create-service-account)\n- [Add your service account as a site owner](#verify-site)\n- [Get an access token](#oauth)\n\nCreate a project for your client\n--------------------------------\n\nBefore you can send requests to the Indexing API, you need to tell Google about your client and\nactivate access to the API. You do this by using the Google API Console to create a project,\nwhich is a named collection of settings and API access information, and register your application.\n\nTo get started using Indexing API, you need to first\n[use\nthe setup tool](https://console.cloud.google.com/start/api?id=indexing.googleapis.com&credential=client_key), which guides you through creating a project in the\nGoogle API Console, enabling the API, and creating credentials.\n\nCreate a service account\n------------------------\n\n1. Open the [**Service accounts** page](https://console.cloud.google.com/iam-admin/serviceaccounts). If prompted, select a project.\n2. Click add **Create Service Account** , enter a name and description for the service account. You can use the default service account ID, or choose a different, unique one. When done click **Create**.\n3. The **Service account permissions (optional)** section that follows is not required. Click **Continue**.\n4. On the **Grant users access to this service account** screen, scroll down to the **Create key** section. Click add **Create key**.\n5. In the side panel that appears, select the format for your key: **JSON** is recommended.\n6. Click **Create** . Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. For information on how to store it securely, see [Managing service account keys](https://cloud.google.com/iam/docs/understanding-service-accounts#managing_service_account_keys).\n7. Click **Close** on the **Private key saved to your computer** dialog, then click **Done** to return to the table of your service accounts.\n\nAdd your service account as a site owner\n----------------------------------------\n\n\nTo add your service account as a site owner:\n\n1. First prove that you own the site, using Search Console, then\n2. Add your service account as an owner.\n\n### 1. Prove that you own the site\n\n\n[Verify ownership of your site](https://support.google.com/webmasters/answer/9008080)\nusing Search Console.\nYou can use any verification method supported by Search Console. You can create either\na Domain property (`example.com`) or a URL-prefix property (`https://example.com`\nor `https://example.com/some/path/`) to represent your site (note that sites are called\n*properties* in Search Console).\n\n### 2. Grant owner status to your service account\n\nNext, add your service account as a\n([delegated](https://support.google.com/webmasters/answer/7687615#permissions-section))\nsite owner:\n\n1. Open [Search Console](https://www.google.com/webmasters/verification/home).\n2. Click the property for which you verified ownership.\n3. In the **Verified owner** list, click **Add an owner**.\n4. Provide your service account email as the delegated owner. You can find your service account email address in two places:\n - The `client_email` field in the JSON private key that you downloaded when you [created your project](#create-project).\n - The **Service account ID** column of the Service Accounts view in the Google Cloud console.\n\n The email address has a format like this: \n \u003cvar translate=\"no\"\u003emy-service-account\u003c/var\u003e`@`\u003cvar translate=\"no\"\u003eproject-name\u003c/var\u003e`.google.com.iam.gserviceaccount.com` \n **For example:** my-service-account@test-project-42.google.com.iam.gserviceaccount.com\n\nGet an access token\n-------------------\n\nEvery call to the Indexing API must be authenticated with an OAuth token that you get\nin exchange for your private key. Each token is good for a span of time.\nGoogle provides [API client libraries](/api-client-library)\nto get OAuth tokens for a number of languages.\n\n### Requirements\n\nWhen submitting a request to the Indexing API, your request must:\n\n1. Use `https://www.googleapis.com/auth/indexing` as the scope.\n2. Use one of the endpoints described in [Using the API](/search/apis/indexing-api/v3/using-api).\n3. Include the [service account access token](#create-service-account).\n4. Define the body of the request as described in [Using the API](/search/apis/indexing-api/v3/using-api).\n\n### Examples\n\nThe following examples show how to obtain an OAuth access token: \n\n#### Python\n\nObtains an OAuth token using the [Google API Client library for Python](/api-client-library/python): \n\n```python\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport httplib2\n\nSCOPES = [ \"https://www.googleapis.com/auth/indexing\" ]\nENDPOINT = \"https://indexing.googleapis.com/v3/urlNotifications:publish\"\n\n# service_account_file.json is the private key that you created for your service account.\nJSON_KEY_FILE = \"service_account_file.json\"\n\ncredentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES)\n\nhttp = credentials.authorize(httplib2.Http())\n\n# Define contents here as a JSON string.\n# This example shows a simple update request.\n# Other types of requests are described in the next step.\n\ncontent = \"\"\"{\n \\\"url\\\": \\\"http://example.com/jobs/42\\\",\n \\\"type\\\": \\\"URL_UPDATED\\\"\n}\"\"\"\n\nresponse, content = http.request(ENDPOINT, method=\"POST\", body=content)\n```\n\n#### Java\n\nObtains an OAuth token using the [API Client Library for Java](/api-client-library/java): \n\n```java\nString scopes = \"https://www.googleapis.com/auth/indexing\";\nString endPoint = \"https://indexing.googleapis.com/v3/urlNotifications:publish\";\n\nJsonFactory jsonFactory = new JacksonFactory();\n\n// service_account_file.json is the private key that you created for your service account.\nInputStream in = IOUtils.toInputStream(\"service_account_file.json\");\n\nGoogleCredential credentials =\n GoogleCredential.fromStream(in, this.httpTransport, jsonFactory).createScoped(Collections.singleton(scopes));\n\nGenericUrl genericUrl = new GenericUrl(endPoint);\nHttpRequestFactory requestFactory = this.httpTransport.createRequestFactory();\n\n// Define content here. The structure of the content is described in the next step.\nString content = \"{\"\n + \"\\\"url\\\": \\\"http://example.com/jobs/42\\\",\"\n + \"\\\"type\\\": \\\"URL_UPDATED\\\",\"\n + \"}\";\n\nHttpRequest request =\n requestFactory.buildPostRequest(genericUrl, ByteArrayContent.fromString(\"application/json\", content));\n\ncredentials.initialize(request);\nHttpResponse response = request.execute();\nint statusCode = response.getStatusCode();\n```\n\n#### PHP\n\nObtains an OAuth token using the [API Client Library for PHP](/api-client-library/php): \n\n```php\nrequire_once 'google-api-php-client/vendor/autoload.php';\n\n$client = new Google_Client();\n\n// service_account_file.json is the private key that you created for your service account.\n$client-\u003esetAuthConfig('service_account_file.json');\n$client-\u003eaddScope('https://www.googleapis.com/auth/indexing');\n\n// Get a Guzzle HTTP Client\n$httpClient = $client-\u003eauthorize();\n$endpoint = 'https://indexing.googleapis.com/v3/urlNotifications:publish';\n\n// Define contents here. The structure of the content is described in the next step.\n$content = '{\n \"url\": \"http://example.com/jobs/42\",\n \"type\": \"URL_UPDATED\"\n}';\n\n$response = $httpClient-\u003epost($endpoint, [ 'body' =\u003e $content ]);\n$status_code = $response-\u003egetStatusCode();\n```\n\n#### Node.js\n\nObtains an OAuth token using the [Node.js Client Library](https://github.com/google/google-api-nodejs-client): \n\n```javascript\nvar request = require(\"request\");\nvar { google } = require(\"googleapis\");\nvar key = require(\"./service_account.json\");\n\nconst jwtClient = new google.auth.JWT(\n key.client_email,\n null,\n key.private_key,\n [\"https://www.googleapis.com/auth/indexing\"],\n null\n);\n\njwtClient.authorize(function(err, tokens) {\n if (err) {\n console.log(err);\n return;\n }\n let options = {\n url: \"https://indexing.googleapis.com/v3/urlNotifications:publish\",\n method: \"POST\",\n // Your options, which must include the Content-Type and auth headers\n headers: {\n \"Content-Type\": \"application/json\"\n },\n auth: { \"bearer\": tokens.access_token },\n // Define contents here. The structure of the content is described in the next step.\n json: {\n \"url\": \"http://example.com/jobs/42\",\n \"type\": \"URL_UPDATED\"\n }\n };\n request(options, function (error, response, body) {\n // Handle the response\n console.log(body);\n });\n});\n```\n\nIn addition to showing how to obtain a token, these examples show where you can add the body of\nthe request message. For information about the types of calls you can make, and the structure of the\nmessage bodies for those calls, see [Using the API](/search/apis/indexing-api/v3/using-api)."]]