Indexing API 사용을 위한 기본 요건

Indexing API를 사용하기 전에 완료해야 하는 몇 가지 작업이 있습니다.

클라이언트용 프로젝트 만들기

Indexing API로 요청을 보내려면 먼저 Google에 클라이언트에 관해 알리고 API에 대한 액세스 권한을 활성화해야 합니다. Google API 콘솔을 사용하여 프로젝트(설정과 API 액세스 정보를 묶어 이름을 지정한 모음)를 만든 다음 애플리케이션을 등록하면 됩니다.

Indexing API를 사용하려면 먼저 설정 도구를 사용하여 Google API 콘솔에서 프로젝트를 만들고, API를 사용 설정하고, 사용자 인증 정보를 생성하는 방법을 알아보시기 바랍니다.

서비스 계정 만들기

  1. 서비스 계정 페이지를 엽니다. 메시지가 표시되면 프로젝트를 선택합니다.
  2. 서비스 계정 만들기를 클릭한 다음 서비스 계정의 이름과 설명을 입력합니다. 기본 서비스 계정 ID를 사용하거나 다른 고유한 ID를 선택할 수도 있습니다. 완료하면 만들기를 클릭합니다.
  3. 이어지는 서비스 계정 권한(선택사항) 섹션은 선택하지 않아도 됩니다. 계속을 클릭합니다.
  4. 사용자에게 이 서비스 계정에 대한 액세스 권한 부여 화면에서 키 만들기 섹션이 나올 때까지 아래로 스크롤합니다. 키 만들기를 클릭합니다.
  5. 표시되는 측면 패널에서 키에 사용할 형식을 선택합니다. JSON을 사용하는 것이 좋습니다.
  6. 만들기를 클릭합니다. 새로운 공개 키/비공개 키 쌍이 생성되어 기기에 다운로드됩니다. 생성된 파일은 이 키의 유일한 사본으로 사용됩니다. 키를 안전하게 보관하는 방법을 자세히 알아보려면 서비스 계정 키 관리를 참조하세요.
  7. 비공개 키가 컴퓨터에 저장됨 대화상자에서 닫기를 클릭한 다음 완료를 클릭하여 서비스 계정 표로 돌아갑니다.

서비스 계정을 사이트 소유자로 추가하기

서비스 계정을 사이트 소유자로 추가하려면 다음 안내를 따르세요.

  1. 먼저 Search Console을 사용하여 사이트의 소유자임을 입증합니다.
  2. 서비스 계정을 소유자로 추가합니다.

1. 사이트 소유자임을 증명

Search Console을 사용하여 사이트의 소유권을 인증받아야 합니다. Search Console에서 지원되는 모든 인증 방법을 사용할 수 있습니다. 도메인 속성(example.com) 또는 URL 접두어 속성(https://example.com 또는 https://example.com/some/path/)을 만들어 사이트를 나타낼 수 있습니다. 참고로, Search Console에서는 사이트를 속성이라고 합니다.

2. 서비스 계정에 소유자 상태 부여

그다음으로, 서비스 계정을 위임된 사이트 소유자로 추가합니다.

  1. 웹마스터 센터를 엽니다.
  2. 소유권을 인증한 속성을 클릭합니다.
  3. 인증된 소유자 목록에서 소유자 추가를 클릭합니다.
  4. 서비스 계정 이메일을 위임된 소유자로 제공합니다. 서비스 계정 이메일 주소는 다음의 두 곳에서 확인할 수 있습니다.
    • 프로젝트를 생성할 때 다운로드한 JSON 비공개 키의 client_email 필드
    • Developers Console 내 서비스 계정 뷰의 서비스 계정 ID
    이메일 주소의 형식은 다음과 같습니다.
    my-service-account@project-name.google.com.iam.gserviceaccount.com
    예: my-service-account@test-project-42.google.com.iam.gserviceaccount.com

액세스 토큰 가져오기

모든 Indexing API 호출은 비공개 키 대신 가져오는 OAuth 토큰을 사용하여 인증해야 합니다. 각 토큰은 일정 기간 동안 유효합니다. Google에서는 여러 언어로 OAuth 토큰을 가져올 수 있는 API 클라이언트 라이브러리를 제공합니다.

요건

Indexing API에 요청을 제출할 때 요청은 다음 요건을 충족해야 합니다.

  1. https://www.googleapis.com/auth/indexing을 범위로 사용합니다.
  2. API 사용에 설명된 엔드포인트 중 하나를 사용합니다.
  3. 서비스 계정 액세스 토큰을 포함합니다.
  4. API 사용에 설명된 대로 요청의 본문을 정의합니다.

다음 예에서 OAuth 액세스 토큰을 받는 방법을 확인할 수 있습니다.

Python

Python용 Google API 클라이언트 라이브러리를 사용하여 OAuth 토큰 받기:

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)

자바

자바용 API 클라이언트 라이브러리를 사용하여 OAuth 토큰 받기:

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

PHP용 API 클라이언트 라이브러리를 사용하여 OAuth 토큰 받기:

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

Node.js 클라이언트 라이브러리를 사용하여 OAuth 토큰 받기:

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

이 예시를 통해 토큰을 받는 방법뿐 아니라 요청 메시지 본문을 어디에 추가할 수 있는지도 알 수 있습니다. 가능한 호출 유형과 이러한 호출의 메시지 본문 구조를 자세히 알아보려면 API 사용을 참조하세요.