# Prerequisites for the Indexing API

Before you can start using the Indexing API, there are a few
things you need to do, if you haven't done them already:

- [Create a project for your client](https://developers.google.com/search/apis/indexing-api/v3/prereqs#create-project)
- [Create a service account](https://developers.google.com/search/apis/indexing-api/v3/prereqs#create-service-account)
- [Add your service account as a site owner](https://developers.google.com/search/apis/indexing-api/v3/prereqs#verify-site)
- [Get an access token](https://developers.google.com/search/apis/indexing-api/v3/prereqs#oauth)

## Create a project for your client

Before you can send requests to the Indexing API, you need to tell Google about your client and
activate access to the API. You do this by using the Google API Console to create a project,
which is a named collection of settings and API access information, and register your application.

To get started using Indexing API, you need to first
[use
the 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
Google API Console and enabling the API.

## Create a service account

1. Open the [**Service accounts** page](https://console.cloud.google.com/iam-admin/serviceaccounts). If prompted, select a project.
2. Click **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**.
3. The **Service account permissions (optional)** section that follows is not required. Click **Continue**.
4. On the **Grant users access to this service account** screen, scroll down to the **Create key** section. Click **Create key**.
5. In the side panel that appears, select the format for your key: **JSON** is recommended.
6. 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).
7. Click **Close** on the **Private key saved to your computer** dialog, then click **Done** to return to the table of your service accounts.

## Add your service account as a site owner


To add your service account as a site owner:

1. First prove that you own the site, using Search Console, then
2. Add your service account as an owner.

### 1. Prove that you own the site


[Verify ownership of your site](https://support.google.com/webmasters/answer/9008080)
using Search Console.
You can use any verification method supported by Search Console. You can create either
a Domain property (`example.com`) or a URL-prefix property (`https://example.com`
or `https://example.com/some/path/`) to represent your site (note that sites are called
*properties* in Search Console).

### 2. Grant owner status to your service account

Next, add your service account as a
([delegated](https://support.google.com/webmasters/answer/7687615#permissions-section))
site owner:

1. Open [Search Console](https://www.google.com/webmasters/verification/home).
2. Click the property for which you verified ownership.
3. In the **Verified owner** list, click **Add an owner**.
4. Provide your service account email as the delegated owner. You can find your service account email address in two places:
   - The `client_email` field in the JSON private key that you downloaded when you [created your project](https://developers.google.com/search/apis/indexing-api/v3/prereqs#create-project).
   - The **Service account ID** column of the Service Accounts view in the Google Cloud console.

   The email address has a format like this:  
   `my-service-account@project-name.google.com.iam.gserviceaccount.com`  
   **For example:** my-service-account@test-project-42.google.com.iam.gserviceaccount.com

## Get an access token

Every call to the Indexing API must be authenticated with an OAuth token that you get
in exchange for your private key. Each token is good for a span of time.
Google provides [API client libraries](https://developers.google.com/api-client-library)
to get OAuth tokens for a number of languages.

### Requirements

When submitting a request to the Indexing API, your request must:

1. Use `https://www.googleapis.com/auth/indexing` as the scope.
2. Use one of the endpoints described in [Using the API](https://developers.google.com/search/apis/indexing-api/v3/using-api).
3. Include the [service account access token](https://developers.google.com/search/apis/indexing-api/v3/prereqs#create-service-account).
4. Define the body of the request as described in [Using the API](https://developers.google.com/search/apis/indexing-api/v3/using-api).

### Examples

The following examples show how to obtain an OAuth access token:

#### Python

Obtains an OAuth token using the [Google API Client library for Python](https://developers.google.com/api-client-library/python):

```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

Obtains an OAuth token using the [API Client Library for Java](https://developers.google.com/api-client-library/java):

```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

Obtains an OAuth token using the [API Client Library for PHP](https://developers.google.com/api-client-library/php):

```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

Obtains an OAuth token using the [Node.js Client Library](https://github.com/google/google-api-nodejs-client):

```javascript
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);
  });
});
```

In addition to showing how to obtain a token, these examples show where you can add the body of
the request message. For information about the types of calls you can make, and the structure of the
message bodies for those calls, see [Using the API](https://developers.google.com/search/apis/indexing-api/v3/using-api).