Mengelola kunci API

Halaman ini menjelaskan cara membuat, mengedit, dan membatasi kunci API. Untuk mengetahui informasi tentang cara menggunakan kunci API untuk mengakses Google API, lihat Menggunakan kunci API untuk mengakses API.

Pengantar kunci API

Ada dua jenis kunci API: kunci API standar, dan kunci API yang telah diikat ke akun layanan.

Kunci API standar

Kunci API standar menyediakan cara untuk mengaitkan permintaan dengan project untuk tujuan penagihan dan kuota. Saat Anda menggunakan kunci API standar (kunci API yang belum terikat ke akun layanan) untuk mengakses API, kunci API tidak mengidentifikasi akun utama. Tanpa entity utama, permintaan tidak dapat menggunakan Identity and Access Management (IAM) untuk memeriksa apakah pemanggil diizinkan untuk melakukan operasi yang diminta.

Kunci API standar dapat digunakan dengan API apa pun yang menerima kunci API, kecuali jika pembatasan API telah ditambahkan ke kunci tersebut. Kunci API standar tidak dapat digunakan dengan layanan yang tidak menerima kunci API, termasuk dalam mode ekspres.

Kunci API yang terikat ke akun layanan

Kunci API yang terikat ke akun layanan akan memberikan identitas dan otorisasi akun layanan ke permintaan. Saat Anda menggunakan kunci API yang telah diikat ke akun layanan untuk mengakses API, permintaan Anda diproses seolah-olah Anda menggunakan akun layanan yang terikat untuk membuat permintaan.

Satu-satunya API yang mendukung kunci API terikat adalah aiplatform.googleapis.com.

Pengikatan kunci ke akun layanan dicegah oleh batasan kebijakan organisasi default. Untuk mengubahnya, lihat Mengaktifkan pengikatan kunci ke akun layanan.

Komponen kunci API

Kunci API memiliki komponen berikut, yang memungkinkan Anda mengelola dan menggunakan kunci:

String
String kunci API adalah string terenkripsi, misalnya, AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe. Saat menggunakan kunci API untuk mengakses API, Anda akan selalu menggunakan string kunci tersebut. Kunci API tidak memiliki file JSON terkait.
ID
ID kunci API digunakan oleh alat administratif Google Cloud untuk mengidentifikasi kunci secara unik. ID kunci tidak dapat digunakan untuk mengakses API. ID kunci dapat ditemukan di URL halaman edit kunci di konsol Google Cloud . Anda juga bisa mendapatkan ID kunci dengan menggunakan Google Cloud CLI untuk mencantumkan kunci di project Anda.
Nama tampilan
Nama tampilan adalah nama deskriptif opsional untuk kunci, yang dapat Anda tetapkan saat membuat atau mengupdate kunci.
Akun layanan terikat
Kunci API
yang terikat ke akun layanan mencakup alamat email akun layanan tersebut.

Sebelum memulai

Selesaikan tugas berikut untuk menggunakan contoh di halaman ini.

Menyiapkan autentikasi

Select the tab for how you plan to use the samples on this page:

Console

When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

gcloud

    In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

    C++

    Untuk menggunakan contoh C++ di halaman ini dalam lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Untuk mengetahui informasi selengkapnya, lihat Menyiapkan ADC untuk lingkungan pengembangan lokal dalam dokumentasi autentikasi Google Cloud .

    Java

    Untuk menggunakan contoh Java di halaman ini dalam lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Untuk mengetahui informasi selengkapnya, lihat Menyiapkan ADC untuk lingkungan pengembangan lokal dalam dokumentasi autentikasi Google Cloud .

    Python

    Untuk menggunakan contoh Python di halaman ini dalam lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Untuk mengetahui informasi selengkapnya, lihat Menyiapkan ADC untuk lingkungan pengembangan lokal dalam dokumentasi autentikasi Google Cloud .

    REST

    Untuk menggunakan contoh REST API di halaman ini dalam lingkungan pengembangan lokal, gunakan kredensial yang Anda berikan ke gcloud CLI.

      After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    Untuk mengetahui informasi selengkapnya, lihat Melakukan autentikasi untuk menggunakan REST dalam dokumentasi autentikasi Google Cloud .

    Peran yang diperlukan

    Untuk mendapatkan izin yang Anda perlukan untuk mengelola kunci API, minta administrator Anda untuk memberi Anda peran IAM berikut di project Anda:

    Untuk mengetahui informasi selengkapnya tentang cara memberikan peran, lihat Mengelola akses ke project, folder, dan organisasi.

    Anda mungkin juga bisa mendapatkan izin yang diperlukan melalui peran khusus atau peran bawaan lainnya.

    Mengaktifkan pengikatan kunci ke akun layanan

    Sebelum dapat mengikat kunci API ke akun layanan, Anda harus menetapkan batasan kebijakan organisasi constraints/iam.managed.disableServiceAccountApiKeyCreation ke false terlebih dahulu. Mengubah kebijakan organisasi memerlukan resource organisasi yang terkait. Project tanpa organisasi tidak didukung.

    Untuk mengubah batasan kebijakan, selesaikan petunjuk berikut.

    Konsol

    1. Di konsol Google Cloud , buka halaman Kebijakan organisasi.

      Buka Organization policies

    2. Beralihlah ke organisasi, folder, atau project yang ingin Anda ubah kebijakannya.

    3. Di kotak Filter, masukkan Block service, lalu klik nama filter Blokir binding kunci API akun layanan.

    4. Klik Manage Policy.

    5. Di bagian Sumber kebijakan, pilih Ganti kebijakan induk.

    6. Klik Tambahkan aturan, lalu setel Pemberlakuan ke Nonaktif.

    7. Klik Selesai.

    8. Opsional: Klik Uji perubahan untuk mendapatkan insight tentang kemungkinan pelanggaran atau gangguan kepatuhan yang disebabkan oleh usulan kebijakan.

    9. Klik Setel kebijakan.

    gcloud

    1. Buat file bernama spec.yaml, dengan konten berikut:

      name: SCOPE/SCOPE_ID/policies/iam.managed.disableServiceAccountApiKeyCreation
      spec:
        rules:
        - enforce: false
      

      Berikan nilai berikut:

      • SCOPE: organizations, folders, atau projects.

      • SCOPE_ID: Bergantung pada SCOPE, ID organisasi, folder, atau project tempat kebijakan organisasi diterapkan.

    2. Jalankan perintah gcloud berikut untuk mengizinkan pengikatan kunci API ke akun layanan:

      gcloud org-policies set-policy spec.yaml \
          --update-mask spec
      

    Membuat kunci API

    Untuk membuat kunci API, gunakan salah satu opsi berikut:

    Konsol

    1. Di konsol Google Cloud , buka halaman Credentials:

      Buka Kredensial

    2. Klik Create credentials, lalu pilih API key dari menu.

    3. Opsional: Untuk mengikat kunci API ke akun layanan, centang kotak Authenticate API calls through a service account, lalu klik Select a service account untuk memilih akun layanan yang ingin Anda ikat ke kunci.

      Untuk mengetahui informasi selengkapnya, lihat Kunci API yang terikat ke akun layanan.

    4. Tambahkan pembatasan kunci API.

      Membatasi kunci API adalah praktik terbaik. Untuk mengetahui informasi selengkapnya, lihat artikel Menerapkan pembatasan kunci API.

    5. Klik Buat. Dialog API key created akan menampilkan string untuk kunci yang baru dibuat.

    gcloud

    Gunakan perintah gcloud services api-keys create untuk membuat kunci API.

    Ganti DISPLAY_NAME dengan nama deskriptif untuk kunci Anda.

     gcloud services api-keys create \
         --display-name=DISPLAY_NAME
    

    Opsional: Untuk mengikat kunci API ke akun layanan, gunakan gcloud beta sebagai gantinya, dengan tanda --service-account:

     gcloud beta services api-keys create \
         --display-name=DISPLAY_NAME \
         --service-account=SERVICE_ACCOUNT_EMAIL_ADDRESS
    

    Untuk mengetahui informasi selengkapnya, lihat Kunci API yang terikat ke akun layanan.

    C++

    Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci API.

    #include "google/cloud/apikeys/v2/api_keys_client.h"
    #include "google/cloud/location.h"
    
    google::api::apikeys::v2::Key CreateApiKey(
        google::cloud::apikeys_v2::ApiKeysClient client,
        google::cloud::Location location, std::string display_name) {
      google::api::apikeys::v2::CreateKeyRequest request;
      request.set_parent(location.FullName());
      request.mutable_key()->set_display_name(std::move(display_name));
      // As an example, restrict the API key's scope to the Natural Language API.
      request.mutable_key()->mutable_restrictions()->add_api_targets()->set_service(
          "language.googleapis.com");
    
      // Create the key, blocking on the result.
      auto key = client.CreateKey(request).get();
      if (!key) throw std::move(key.status());
      std::cout << "Successfully created an API key: " << key->name() << "\n";
    
      // For authenticating with the API key, use the value in `key->key_string()`.
    
      // The API key's resource name is the value in `key->name()`. Use this to
      // refer to the specific key in a `GetKey()` or `DeleteKey()` RPC.
      return *key;
    }

    Java

    Untuk menjalankan contoh ini, Anda harus menginstal library klien google-cloud-apikeys.

    
    import com.google.api.apikeys.v2.ApiKeysClient;
    import com.google.api.apikeys.v2.ApiTarget;
    import com.google.api.apikeys.v2.CreateKeyRequest;
    import com.google.api.apikeys.v2.Key;
    import com.google.api.apikeys.v2.LocationName;
    import com.google.api.apikeys.v2.Restrictions;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class CreateApiKey {
    
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(Developer): Before running this sample,
        //  1. Replace the variable(s) below.
        //  2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
        //  3. Make sure you have the necessary permission to create API keys.
        String projectId = "GOOGLE_CLOUD_PROJECT_ID";
    
        createApiKey(projectId);
      }
    
      // Creates an API key.
      public static void createApiKey(String projectId)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the `apiKeysClient.close()` method on the client to safely
        // clean up any remaining background resources.
        try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
    
          Key key = Key.newBuilder()
              .setDisplayName("My first API key")
              // Set the API key restriction.
              // You can also set browser/ server/ android/ ios based restrictions.
              // For more information on API key restriction, see:
              // https://cloud.google.com/docs/authentication/api-keys#api_key_restrictions
              .setRestrictions(Restrictions.newBuilder()
                  // Restrict the API key usage by specifying the target service and methods.
                  // The API key can only be used to authenticate the specified methods in the service.
                  .addApiTargets(ApiTarget.newBuilder()
                      .setService("translate.googleapis.com")
                      .addMethods("translate.googleapis.com.TranslateText")
                      .build())
                  .build())
              .build();
    
          // Initialize request and set arguments.
          CreateKeyRequest createKeyRequest = CreateKeyRequest.newBuilder()
              // API keys can only be global.
              .setParent(LocationName.of(projectId, "global").toString())
              .setKey(key)
              .build();
    
          // Make the request and wait for the operation to complete.
          Key result = apiKeysClient.createKeyAsync(createKeyRequest).get(3, TimeUnit.MINUTES);
    
          // For authenticating with the API key, use the value in "result.getKeyString()".
          // To restrict the usage of this API key, use the value in "result.getName()".
          System.out.printf("Successfully created an API key: %s", result.getName());
        }
      }
    }

    Python

    Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci API.

    
    from google.cloud import api_keys_v2
    from google.cloud.api_keys_v2 import Key
    
    
    def create_api_key(project_id: str, suffix: str) -> Key:
        """
        Creates and restrict an API key. Add the suffix for uniqueness.
    
        TODO(Developer):
        1. Before running this sample,
          set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
        2. Make sure you have the necessary permission to create API keys.
    
        Args:
            project_id: Google Cloud project id.
    
        Returns:
            response: Returns the created API Key.
        """
        # Create the API Keys client.
        client = api_keys_v2.ApiKeysClient()
    
        key = api_keys_v2.Key()
        key.display_name = f"My first API key - {suffix}"
    
        # Initialize request and set arguments.
        request = api_keys_v2.CreateKeyRequest()
        request.parent = f"projects/{project_id}/locations/global"
        request.key = key
    
        # Make the request and wait for the operation to complete.
        response = client.create_key(request=request).result()
    
        print(f"Successfully created an API key: {response.name}")
        # For authenticating with the API key, use the value in "response.key_string".
        # To restrict the usage of this API key, use the value in "response.name".
        return response
    
    

    REST

    Gunakan metode keys.create untuk membuat kunci API. Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mendapatkan informasi tentang kunci yang baru.

    Ganti nilai berikut:

    • DISPLAY_NAME: Opsional. Nama deskriptif untuk kunci Anda.
    • PROJECT_ID: ID atau nama project Google Cloud Anda.
    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d {'"displayName" : "DISPLAY_NAME"'} \
    "https://apikeys.googleapis.com/v2/projects/PROJECT/locations/global/keys"

    Opsional: Untuk mengikat kunci API ke akun layanan, gunakan perintah berikut:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d {'"displayName" : "DISPLAY_NAME",
         "serviceAccountEmail" : "SERVICE_ACCOUNT_EMAIL"'} \
    "https://apikeys.googleapis.com/v2/projects/PROJECT/locations/global/keys"

    Untuk mengetahui informasi selengkapnya, lihat Kunci API yang terikat ke akun layanan.

    Untuk informasi lebih lanjut tentang membuat kunci API menggunakan REST API, lihat Membuat kunci API dalam dokumentasi API Keys API.

    Menerapkan pembatasan kunci API

    Kunci API tidak dibatasi secara default. Kunci yang tidak dibatasi tidak aman karena dapat digunakan oleh siapa saja dari mana saja. Untuk aplikasi produksi, Anda harus menetapkan pembatasan aplikasi dan pembatasan API.

    Menambahkan batasan aplikasi

    Pembatasan aplikasi menentukan situs, alamat IP, atau aplikasi mana yang dapat menggunakan kunci API.

    Anda hanya dapat menerapkan satu jenis pembatasan aplikasi dalam satu waktu. Pilih jenis pembatasan berdasarkan jenis aplikasi Anda:

    Opsi Jenis aplikasi Catatan
    Perujuk HTTP Aplikasi web Menentukan situs yang dapat menggunakan kunci tersebut.
    Alamat IP Aplikasi yang dipanggil oleh server tertentu Menentukan server atau cron job yang dapat menggunakan kunci tersebut. Ini adalah satu-satunya batasan yang tersedia jika Anda mengikat kunci API ke akun layanan.
    Aplikasi Android Aplikasi Android Menentukan aplikasi Android yang dapat menggunakan kunci tersebut.
    Aplikasi iOS Aplikasi iOS Menentukan paket iOS yang dapat menggunakan kunci tersebut.

    Perujuk HTTP

    Untuk membatasi situs yang dapat menggunakan kunci API Anda, tambahkan satu atau beberapa pembatasan perujuk HTTP.

    Anda dapat mengganti karakter pengganti (*) untuk subdomain atau jalur, tetapi Anda tidak dapat menyisipkan karakter pengganti ke tengah URL. Misalnya, *.example.com valid, dan menerima semua situs yang diakhiri dengan .example.com. Namun, mysubdomain*.example.com bukan batasan yang valid.

    Nomor port dapat disertakan dalam pembatasan perujuk HTTP. Jika Anda menyertakan nomor port, hanya permintaan yang menggunakan port tersebut yang akan dicocokkan. Jika Anda tidak menentukan nomor port, permintaan dari nomor port mana pun akan dicocokkan.

    Tabel berikut menunjukkan beberapa skenario contoh dan pembatasan browser:

    Skenario Pembatasan
    Mengizinkan URL tertentu Menambahkan URL dengan jalur yang tepat. Contoh:
    www.example.com/path
    www.example.com/path/path

    Beberapa browser menerapkan kebijakan perujuk yang hanya mengirim URL asal untuk permintaan lintas asal. Pengguna browser ini tidak dapat menggunakan kunci dengan pembatasan URL khusus halaman.

    Izinkan URL apa pun di situs Anda Anda harus menetapkan dua URL dalam daftar allowedReferers.
    1. URL untuk domain, tanpa subdomain, dan dengan karakter pengganti untuk jalur. Contoh:
      example.com/*
    2. URL kedua yang menyertakan karakter pengganti untuk subdomain dan karakter pengganti untuk jalur. Contoh:
      *.example.com/*
    Mengizinkan URL apa pun pada subdomain tunggal atau domain tanpa awalan www

    Anda harus menetapkan dua URL dalam daftar allowedReferers untuk mengizinkan seluruh domain:

    1. URL untuk domain, tanpa garis miring setelahnya. Contoh:
      www.example.com
      sub.example.com
      example.com
    2. URL kedua untuk domain yang menyertakan karakter pengganti untuk jalur. Contoh:
      www.example.com/*
      sub.example.com/*
      example.com/*

    Untuk membatasi kunci API Anda ke situs tertentu, gunakan salah satu opsi berikut:

    Konsol

    1. Di konsol Google Cloud , buka halaman Credentials:

      Buka Kredensial

    2. Klik nama kunci API yang ingin Anda batasi.

    3. Di bagian Application restrictions, pilih HTTP referrers.

    4. Untuk setiap batasan yang ingin ditambahkan, klik Add an item, masukkan batasan, lalu klik Done.

    5. Klik Simpan untuk menyimpan perubahan dan kembali ke daftar kunci API.

    gcloud

    1. Dapatkan ID kunci yang ingin Anda batasi.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list untuk mencantumkan kunci di project Anda.

    2. Gunakan perintah gcloud services api-keys update untuk menambahkan batasan perujuk HTTP ke kunci API.

      Ganti nilai berikut:

      • KEY_ID: ID kunci yang ingin Anda batasi.
      • ALLOWED_REFERRER_1: Pembatasan perujuk HTTP Anda.

        Anda dapat menambahkan batasan sebanyak yang diperlukan; gunakan koma untuk memisahkan batasan. Anda harus memberikan semua batasan perujuk dengan perintah update; pembatasan perujuk yang diberikan menggantikan pembatasan perujuk yang ada pada kunci tersebut.

      gcloud services api-keys update KEY_ID \
       --allowed-referrers="ALLOWED_REFERRER_1"

    Java

    Untuk menjalankan contoh ini, Anda harus menginstal library klien google-cloud-apikeys.

    
    import com.google.api.apikeys.v2.ApiKeysClient;
    import com.google.api.apikeys.v2.BrowserKeyRestrictions;
    import com.google.api.apikeys.v2.Key;
    import com.google.api.apikeys.v2.Restrictions;
    import com.google.api.apikeys.v2.UpdateKeyRequest;
    import com.google.protobuf.FieldMask;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class RestrictApiKeyHttp {
    
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(Developer): Before running this sample,
        //  1. Replace the variable(s) below.
        String projectId = "GOOGLE_CLOUD_PROJECT_ID";
    
        // ID of the key to restrict. This ID is auto-created during key creation.
        // This is different from the key string. To obtain the key_id,
        // you can also use the lookup api: client.lookupKey()
        String keyId = "key_id";
    
        restrictApiKeyHttp(projectId, keyId);
      }
    
      // Restricts an API key. To restrict the websites that can use your API key,
      // you add one or more HTTP referrer restrictions.
      public static void restrictApiKeyHttp(String projectId, String keyId)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the `apiKeysClient.close()` method on the client to safely
        // clean up any remaining background resources.
        try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
    
          // Restrict the API key usage to specific websites by adding them
          // to the list of allowed_referrers.
          Restrictions restrictions = Restrictions.newBuilder()
              .setBrowserKeyRestrictions(BrowserKeyRestrictions.newBuilder()
                  .addAllowedReferrers("www.example.com/*")
                  .build())
              .build();
    
          Key key = Key.newBuilder()
              .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
              // Set the restriction(s).
              // For more information on API key restriction, see:
              // https://cloud.google.com/docs/authentication/api-keys
              .setRestrictions(restrictions)
              .build();
    
          // Initialize request and set arguments.
          UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
              .setKey(key)
              .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
              .build();
    
          // Make the request and wait for the operation to complete.
          Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);
    
          // For authenticating with the API key, use the value in "result.getKeyString()".
          System.out.printf("Successfully updated the API key: %s", result.getName());
        }
      }
    }

    Python

    Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci API.

    
    from google.cloud import api_keys_v2
    from google.cloud.api_keys_v2 import Key
    
    
    def restrict_api_key_http(project_id: str, key_id: str) -> Key:
        """
        Restricts an API key. To restrict the websites that can use your API key,
        you add one or more HTTP referrer restrictions.
    
        TODO(Developer): Replace the variables before running this sample.
    
        Args:
            project_id: Google Cloud project id.
            key_id: ID of the key to restrict. This ID is auto-created during key creation.
                This is different from the key string. To obtain the key_id,
                you can also use the lookup api: client.lookup_key()
    
        Returns:
            response: Returns the updated API Key.
        """
    
        # Create the API Keys client.
        client = api_keys_v2.ApiKeysClient()
    
        # Restrict the API key usage to specific websites by adding them to the list of allowed_referrers.
        browser_key_restrictions = api_keys_v2.BrowserKeyRestrictions()
        browser_key_restrictions.allowed_referrers = ["www.example.com/*"]
    
        # Set the API restriction.
        # For more information on API key restriction, see:
        # https://cloud.google.com/docs/authentication/api-keys
        restrictions = api_keys_v2.Restrictions()
        restrictions.browser_key_restrictions = browser_key_restrictions
    
        key = api_keys_v2.Key()
        key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
        key.restrictions = restrictions
    
        # Initialize request and set arguments.
        request = api_keys_v2.UpdateKeyRequest()
        request.key = key
        request.update_mask = "restrictions"
    
        # Make the request and wait for the operation to complete.
        response = client.update_key(request=request).result()
    
        print(f"Successfully updated the API key: {response.name}")
        # Use response.key_string to authenticate.
        return response
    
    

    REST

    1. Dapatkan ID kunci yang ingin Anda batasi.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini menggunakan metode keys.list. ID tercantum di kolom uid respons.

      Ganti PROJECT_ID dengan Google Cloud project ID atau nama project Anda.

      curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    2. Gunakan metode keys.patch untuk menambahkan pembatasan perujuk HTTP pada kunci API.

      Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mengetahui kapan operasi selesai dan mendapatkan status operasi.

      Ganti nilai berikut:

      • ALLOWED_REFERRER_1: Pembatasan perujuk HTTP Anda.

        Anda dapat menambahkan batasan sebanyak yang diperlukan; gunakan koma untuk memisahkan batasan. Anda harus memberikan semua batasan perujuk dengan permintaan tersebut; pembatasan perujuk yang diberikan menggantikan pembatasan perujuk yang ada pada kunci tersebut.

      • PROJECT_ID: Project ID atau nama project Anda. Google Cloud

      • KEY_ID: ID kunci yang ingin Anda batasi.

      curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      --data '{
      "restrictions" : {
      "browserKeyRestrictions": {
        "allowedReferrers": ["ALLOWED_REFERRER_1"]
      }
      }
      }' \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

    Untuk informasi selengkapnya tentang menambahkan pembatasan perujuk HTTP ke kunci menggunakan REST API, lihat Menambahkan pembatasan browser dalam dokumentasi API Keys API.

    Alamat IP

    Anda dapat menentukan satu atau beberapa alamat IP pemanggil, seperti server web atau cron job, yang diizinkan untuk menggunakan kunci API Anda. Anda dapat menentukan alamat IP dalam salah satu format berikut:

    • IPv4 (198.51.100.1)
    • IPv6 (2001:db8::1)
    • Subnet yang menggunakan notasi CIDR (198.51.100.0/24, 2001:db8::/64)

    Penggunaan localhost tidak didukung untuk pembatasan server.

    Untuk membatasi kunci API Anda ke alamat IP tertentu, gunakan salah satu opsi berikut:

    Konsol

    1. Di konsol Google Cloud , buka halaman Credentials:

      Buka Kredensial

    2. Klik nama kunci API yang ingin Anda batasi.

    3. Di bagian Application restrictions, pilih IP addresses.

    4. Untuk setiap alamat IP yang ingin ditambahkan, klik Add an item, masukkan alamat, lalu klik Done.

    5. Klik Simpan untuk menyimpan perubahan dan kembali ke daftar kunci API.

    gcloud

    1. Dapatkan ID kunci yang ingin Anda batasi.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list untuk mencantumkan kunci di project Anda.

    2. Gunakan perintah gcloud services api-keys update untuk menambahkan pembatasan server (alamat IP) ke kunci API.

      Ganti nilai berikut:

      • KEY_ID: ID kunci yang ingin Anda batasi.
      • ALLOWED_IP_ADDR_1: Alamat IP yang diizinkan.

        Anda dapat menambahkan alamat IP sebanyak yang diperlukan; menggunakan koma untuk memisahkan alamat.

      gcloud services api-keys update KEY_ID \
      --allowed-ips="ALLOWED_IP_ADDR_1"

    Java

    Untuk menjalankan contoh ini, Anda harus menginstal library klien google-cloud-apikeys.

    
    import com.google.api.apikeys.v2.ApiKeysClient;
    import com.google.api.apikeys.v2.Key;
    import com.google.api.apikeys.v2.Restrictions;
    import com.google.api.apikeys.v2.ServerKeyRestrictions;
    import com.google.api.apikeys.v2.UpdateKeyRequest;
    import com.google.protobuf.FieldMask;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class RestrictApiKeyServer {
    
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(Developer): Before running this sample,
        //  1. Replace the variable(s) below.
        String projectId = "GOOGLE_CLOUD_PROJECT_ID";
    
        // ID of the key to restrict. This ID is auto-created during key creation.
        // This is different from the key string. To obtain the key_id,
        // you can also use the lookup api: client.lookupKey()
        String keyId = "key_id";
    
        restrictApiKeyServer(projectId, keyId);
      }
    
      // Restricts the API key based on IP addresses. You can specify one or more IP addresses
      // of the callers, for example web servers or cron jobs, that are allowed to use your API key.
      public static void restrictApiKeyServer(String projectId, String keyId)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the `apiKeysClient.close()` method on the client to safely
        // clean up any remaining background resources.
        try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
    
          // Restrict the API key usage by specifying the IP addresses.
          // You can specify the IP addresses in IPv4 or IPv6 or a subnet using CIDR notation.
          Restrictions restrictions = Restrictions.newBuilder()
              .setServerKeyRestrictions(ServerKeyRestrictions.newBuilder()
                  .addAllAllowedIps(Arrays.asList("198.51.100.0/24", "2000:db8::/64"))
                  .build())
              .build();
    
          Key key = Key.newBuilder()
              .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
              // Set the restriction(s).
              // For more information on API key restriction, see:
              // https://cloud.google.com/docs/authentication/api-keys
              .setRestrictions(restrictions)
              .build();
    
          // Initialize request and set arguments.
          UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
              .setKey(key)
              .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
              .build();
    
          // Make the request and wait for the operation to complete.
          Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);
    
          // For authenticating with the API key, use the value in "result.getKeyString()".
          System.out.printf("Successfully updated the API key: %s", result.getName());
        }
      }
    }

    Python

    Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci API.

    
    from google.cloud import api_keys_v2
    from google.cloud.api_keys_v2 import Key
    
    
    def restrict_api_key_server(project_id: str, key_id: str) -> Key:
        """
        Restricts the API key based on IP addresses. You can specify one or more IP addresses of the callers,
        for example web servers or cron jobs, that are allowed to use your API key.
    
        TODO(Developer): Replace the variables before running this sample.
    
        Args:
            project_id: Google Cloud project id.
            key_id: ID of the key to restrict. This ID is auto-created during key creation.
                This is different from the key string. To obtain the key_id,
                you can also use the lookup api: client.lookup_key()
    
        Returns:
            response: Returns the updated API Key.
        """
    
        # Create the API Keys client.
        client = api_keys_v2.ApiKeysClient()
    
        # Restrict the API key usage by specifying the IP addresses.
        # You can specify the IP addresses in IPv4 or IPv6 or a subnet using CIDR notation.
        server_key_restrictions = api_keys_v2.ServerKeyRestrictions()
        server_key_restrictions.allowed_ips = ["198.51.100.0/24", "2000:db8::/64"]
    
        # Set the API restriction.
        # For more information on API key restriction, see:
        # https://cloud.google.com/docs/authentication/api-keys
        restrictions = api_keys_v2.Restrictions()
        restrictions.server_key_restrictions = server_key_restrictions
    
        key = api_keys_v2.Key()
        key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
        key.restrictions = restrictions
    
        # Initialize request and set arguments.
        request = api_keys_v2.UpdateKeyRequest()
        request.key = key
        request.update_mask = "restrictions"
    
        # Make the request and wait for the operation to complete.
        response = client.update_key(request=request).result()
    
        print(f"Successfully updated the API key: {response.name}")
        # Use response.key_string to authenticate.
        return response
    
    

    REST

    1. Dapatkan ID kunci yang ingin Anda batasi.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini menggunakan metode keys.list. ID tercantum di kolom uid respons.

      Ganti PROJECT_ID dengan Google Cloud project ID atau nama project Anda.

      curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    2. Gunakan metode keys.patch untuk menambahkan pembatasan server (alamat IP) ke kunci API.

      Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mengetahui kapan operasi selesai dan mendapatkan status operasi.

      Ganti nilai berikut:

      • ALLOWED_IP_ADDR_1: Alamat IP yang diizinkan.

        Anda dapat menambahkan alamat IP sebanyak yang diperlukan; menggunakan koma untuk memisahkan batasan. Anda harus memberikan semua alamat IP dengan permintaan; pembatasan perujuk yang disediakan menggantikan pembatasan alamat IP yang ada pada kunci tersebut.

      • PROJECT_ID: Project ID atau nama project Anda. Google Cloud

      • KEY_ID: ID kunci yang ingin Anda batasi.

      curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      --data '{
      "restrictions" : {
        "serverKeyRestrictions": {
          "allowedIps": ["ALLOWED_IP_ADDR_1"]
        }
      }
      }' \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

    Untuk informasi selengkapnya tentang menambahkan pembatasan alamat IP ke kunci menggunakan REST API, lihat Menambahkan pembatasan server dalam dokumentasi API Keys API.

    Aplikasi Android

    Anda dapat membatasi penggunaan kunci API untuk aplikasi Android tertentu. Anda harus memberikan nama paket dan sidik jari sertifikat SHA-1 20 byte untuk setiap aplikasi.

    Saat menggunakan kunci API dalam permintaan, Anda harus menentukan nama paket dan sidik jari sertifikat menggunakan header HTTP berikut:

    • X-Android-Package
    • X-Android-Cert

    Untuk membatasi kunci API Anda ke satu atau beberapa aplikasi Android, gunakan salah satu opsi berikut:

    Konsol

    1. Di konsol Google Cloud , buka halaman Credentials:

      Buka Kredensial

    2. Klik nama kunci API yang ingin Anda batasi.

    3. Di bagian Application restrictions, pilih Android apps.

    4. Untuk setiap aplikasi Android yang ingin ditambahkan, klik Add an item dan masukkan nama paket serta sidik jari sertifikat SHA-1, lalu klik Done.

    5. Klik Simpan untuk menyimpan perubahan dan kembali ke daftar kunci API.

    gcloud

    1. Dapatkan ID kunci yang ingin Anda batasi.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list untuk mencantumkan kunci di project Anda.

    2. Gunakan perintah gcloud services api-keys update untuk menentukan aplikasi Android yang dapat menggunakan kunci API.

      Ganti nilai berikut:

      • KEY_ID: ID kunci yang ingin Anda batasi.
      • SHA1_FINGERPRINT dan PACKAGE_NAME: Informasi aplikasi untuk aplikasi Android yang dapat menggunakan kunci tersebut.

        Anda dapat menambahkan aplikasi sebanyak yang diperlukan; gunakan flag --allowed-application tambahan.

      gcloud services api-keys update KEY_ID \
      --allowed-application=sha1_fingerprint=SHA1_FINGERPRINT_1,package_name=PACKAGE_NAME_1 \
      --allowed-application=sha1_fingerprint=SHA1_FINGERPRINT_2,package_name=PACKAGE_NAME_2

    Java

    Untuk menjalankan contoh ini, Anda harus menginstal library klien google-cloud-apikeys.

    
    import com.google.api.apikeys.v2.AndroidApplication;
    import com.google.api.apikeys.v2.AndroidKeyRestrictions;
    import com.google.api.apikeys.v2.ApiKeysClient;
    import com.google.api.apikeys.v2.Key;
    import com.google.api.apikeys.v2.Restrictions;
    import com.google.api.apikeys.v2.UpdateKeyRequest;
    import com.google.protobuf.FieldMask;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class RestrictApiKeyAndroid {
    
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(Developer): Before running this sample,
        //  1. Replace the variable(s) below.
        String projectId = "GOOGLE_CLOUD_PROJECT_ID";
    
        // ID of the key to restrict. This ID is auto-created during key creation.
        // This is different from the key string. To obtain the key_id,
        // you can also use the lookup api: client.lookupKey()
        String keyId = "key_id";
    
        restrictApiKeyAndroid(projectId, keyId);
      }
    
      // Restricts an API key based on android applications.
      // Specifies the Android application that can use the key.
      public static void restrictApiKeyAndroid(String projectId, String keyId)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the `apiKeysClient.close()` method on the client to safely
        // clean up any remaining background resources.
        try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
    
          // Restrict the API key usage by specifying the allowed android applications.
          Restrictions restrictions = Restrictions.newBuilder()
              .setAndroidKeyRestrictions(AndroidKeyRestrictions.newBuilder()
                  .addAllowedApplications(AndroidApplication.newBuilder()
                      // Specify the android application's package name and SHA1 fingerprint.
                      .setPackageName("com.google.appname")
                      .setSha1Fingerprint("0873D391E987982FBBD30873D391E987982FBBD3")
                      .build())
                  .build())
              .build();
    
          Key key = Key.newBuilder()
              .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
              // Set the restriction(s).
              // For more information on API key restriction, see:
              // https://cloud.google.com/docs/authentication/api-keys
              .setRestrictions(restrictions)
              .build();
    
          // Initialize request and set arguments.
          UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
              .setKey(key)
              .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
              .build();
    
          // Make the request and wait for the operation to complete.
          Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);
    
          // For authenticating with the API key, use the value in "result.getKeyString()".
          System.out.printf("Successfully updated the API key: %s", result.getName());
        }
      }
    }

    Python

    Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci API.

    
    from google.cloud import api_keys_v2
    from google.cloud.api_keys_v2 import Key
    
    
    def restrict_api_key_android(project_id: str, key_id: str) -> Key:
        """
        Restricts an API key based on android applications.
    
        Specifies the Android application that can use the key.
    
        TODO(Developer): Replace the variables before running this sample.
    
        Args:
            project_id: Google Cloud project id.
            key_id: ID of the key to restrict. This ID is auto-created during key creation.
                This is different from the key string. To obtain the key_id,
                you can also use the lookup api: client.lookup_key()
    
        Returns:
            response: Returns the updated API Key.
        """
    
        # Create the API Keys client.
        client = api_keys_v2.ApiKeysClient()
    
        # Specify the android application's package name and SHA1 fingerprint.
        allowed_application = api_keys_v2.AndroidApplication()
        allowed_application.package_name = "com.google.appname"
        allowed_application.sha1_fingerprint = "0873D391E987982FBBD30873D391E987982FBBD3"
    
        # Restrict the API key usage by specifying the allowed applications.
        android_key_restriction = api_keys_v2.AndroidKeyRestrictions()
        android_key_restriction.allowed_applications = [allowed_application]
    
        # Set the restriction(s).
        # For more information on API key restriction, see:
        # https://cloud.google.com/docs/authentication/api-keys
        restrictions = api_keys_v2.Restrictions()
        restrictions.android_key_restrictions = android_key_restriction
    
        key = api_keys_v2.Key()
        key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
        key.restrictions = restrictions
    
        # Initialize request and set arguments.
        request = api_keys_v2.UpdateKeyRequest()
        request.key = key
        request.update_mask = "restrictions"
    
        # Make the request and wait for the operation to complete.
        response = client.update_key(request=request).result()
    
        print(f"Successfully updated the API key: {response.name}")
        # Use response.key_string to authenticate.
        return response
    
    

    REST

    1. Dapatkan ID kunci yang ingin Anda batasi.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini menggunakan metode keys.list. ID tercantum di kolom uid respons.

      Ganti PROJECT_ID dengan Google Cloud project ID atau nama project Anda.

      curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    2. Gunakan metode keys.patch untuk menentukan aplikasi Android yang dapat menggunakan kunci API.

      Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mengetahui kapan operasi selesai dan mendapatkan status operasi.

      Ganti nilai berikut:

      • SHA1_FINGERPRINT_1 dan PACKAGE_NAME_1: Informasi aplikasi untuk aplikasi Android yang dapat menggunakan kunci tersebut.

        Anda dapat menambahkan informasi untuk aplikasi sebanyak yang dibutuhkan; gunakan koma untuk memisahkan objek AndroidApplication. Anda harus memberikan permintaan kepada semua aplikasi; aplikasi yang disediakan menggantikan aplikasi yang diizinkan pada kunci tersebut.

      • PROJECT_ID: Project ID atau nama project Anda. Google Cloud

      • KEY_ID: ID kunci yang ingin Anda batasi.

      curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      --data '{
      "restrictions" : {
      "androidKeyRestrictions": {
        "allowedApplications": [
          {
            "sha1Fingerprint": "SHA1_FINGERPRINT_1",
            "packageName": "PACKAGE_NAME_1"
          },
       ]
      }
      }
      }' \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

    Untuk informasi selengkapnya tentang menambahkan pembatasan aplikasi Android ke kunci menggunakan REST API, lihat Menambahkan pembatasan Android dalam dokumentasi API Keys API.

    Aplikasi iOS

    Anda dapat membatasi penggunaan kunci API untuk aplikasi iOS tertentu dengan memberikan ID paket setiap aplikasi.

    Jika menggunakan kunci API dalam permintaan, Anda harus menentukan ID paket menggunakan header HTTP X-Ios-Bundle-Identifier.

    Untuk membatasi kunci API Anda ke satu atau beberapa aplikasi iOS, gunakan salah satu opsi berikut:

    Konsol

    1. Di konsol Google Cloud , buka halaman Credentials:

      Buka Kredensial

    2. Klik nama kunci API yang ingin Anda batasi.

    3. Di bagian Application restrictions, pilih iOS apps.

    4. Untuk setiap aplikasi iOS yang ingin Anda tambahkan, klik Add an item dan masukkan ID paket, lalu klik Done.

    5. Klik Simpan untuk menyimpan perubahan dan kembali ke daftar kunci API.

    gcloud

    1. Dapatkan ID kunci yang ingin Anda batasi.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list untuk mencantumkan kunci di project Anda.

    2. Gunakan metode gcloud services api-keys update untuk menentukan aplikasi iOS yang dapat menggunakan kunci tersebut.

      Ganti nilai berikut:

      • KEY_ID: ID kunci yang ingin Anda batasi.
      • ALLOWED_BUNDLE_ID: ID paket aplikasi iOS tempat Anda ingin dapat menggunakan kunci API ini.

        Anda dapat menambahkan ID paket sebanyak yang diperlukan; menggunakan koma untuk memisahkan ID.

      gcloud services api-keys update KEY_ID \
      --allowed-bundle-ids=ALLOWED_BUNDLE_ID_1,ALLOWED_BUNDLE_ID_2

    Java

    Untuk menjalankan contoh ini, Anda harus menginstal library klien google-cloud-apikeys.

    
    import com.google.api.apikeys.v2.ApiKeysClient;
    import com.google.api.apikeys.v2.IosKeyRestrictions;
    import com.google.api.apikeys.v2.Key;
    import com.google.api.apikeys.v2.Restrictions;
    import com.google.api.apikeys.v2.UpdateKeyRequest;
    import com.google.protobuf.FieldMask;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class RestrictApiKeyIos {
    
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(Developer): Before running this sample,
        //  1. Replace the variable(s) below.
        String projectId = "GOOGLE_CLOUD_PROJECT_ID";
    
        // ID of the key to restrict. This ID is auto-created during key creation.
        // This is different from the key string. To obtain the key_id,
        // you can also use the lookup api: client.lookupKey()
        String keyId = "key_id";
    
        restrictApiKeyIos(projectId, keyId);
      }
    
      // Restricts an API key. You can restrict usage of an API key to specific iOS apps
      // by providing the bundle ID of each app.
      public static void restrictApiKeyIos(String projectId, String keyId)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the `apiKeysClient.close()` method on the client to safely
        // clean up any remaining background resources.
        try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
    
          // Restrict the API key usage by specifying the bundle ID(s)
          // of iOS app(s) that can use the key.
          Restrictions restrictions = Restrictions.newBuilder()
              .setIosKeyRestrictions(IosKeyRestrictions.newBuilder()
                  .addAllAllowedBundleIds(Arrays.asList("com.google.gmail", "com.google.drive"))
                  .build())
              .build();
    
          Key key = Key.newBuilder()
              .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
              // Set the restriction(s).
              // For more information on API key restriction, see:
              // https://cloud.google.com/docs/authentication/api-keys
              .setRestrictions(restrictions)
              .build();
    
          // Initialize request and set arguments.
          UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
              .setKey(key)
              .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
              .build();
    
          // Make the request and wait for the operation to complete.
          Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);
    
          // For authenticating with the API key, use the value in "result.getKeyString()".
          System.out.printf("Successfully updated the API key: %s", result.getName());
        }
      }
    }

    Python

    Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci API.

    
    from google.cloud import api_keys_v2
    from google.cloud.api_keys_v2 import Key
    
    
    def restrict_api_key_ios(project_id: str, key_id: str) -> Key:
        """
        Restricts an API key. You can restrict usage of an API key to specific iOS apps
        by providing the bundle ID of each app.
    
        TODO(Developer): Replace the variables before running this sample.
    
        Args:
            project_id: Google Cloud project id.
            key_id: ID of the key to restrict. This ID is auto-created during key creation.
                This is different from the key string. To obtain the key_id,
                you can also use the lookup api: client.lookup_key()
    
        Returns:
            response: Returns the updated API Key.
        """
    
        # Create the API Keys client.
        client = api_keys_v2.ApiKeysClient()
    
        # Restrict the API key usage by specifying the bundle ID(s) of iOS app(s) that can use the key.
        ios_key_restrictions = api_keys_v2.IosKeyRestrictions()
        ios_key_restrictions.allowed_bundle_ids = ["com.google.gmail", "com.google.drive"]
    
        # Set the API restriction.
        # For more information on API key restriction, see:
        # https://cloud.google.com/docs/authentication/api-keys
        restrictions = api_keys_v2.Restrictions()
        restrictions.ios_key_restrictions = ios_key_restrictions
    
        key = api_keys_v2.Key()
        key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
        key.restrictions = restrictions
    
        # Initialize request and set arguments.
        request = api_keys_v2.UpdateKeyRequest()
        request.key = key
        request.update_mask = "restrictions"
    
        # Make the request and wait for the operation to complete.
        response = client.update_key(request=request).result()
    
        print(f"Successfully updated the API key: {response.name}")
        # Use response.key_string to authenticate.
        return response
    
    

    REST

    1. Dapatkan ID kunci yang ingin Anda batasi.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini menggunakan metode keys.list. ID tercantum di kolom uid respons.

      Ganti PROJECT_ID dengan Google Cloud project ID atau nama project Anda.

      curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    2. Gunakan metode keys.patch untuk menentukan aplikasi iOS yang dapat menggunakan kunci API.

      Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mengetahui kapan operasi selesai dan mendapatkan status operasi.

      Ganti nilai berikut:

      • ALLOWED_BUNDLE_ID: ID paket aplikasi iOS yang dapat menggunakan kunci.

        Anda dapat menambahkan informasi untuk aplikasi sebanyak yang dibutuhkan; gunakan koma untuk memisahkan ID paket. Anda harus memberikan semua ID paket bersama permintaan; ID paket yang diberikan akan menggantikan aplikasi yang diizinkan pada kunci tersebut.

      • PROJECT_ID: Project ID atau nama project Anda. Google Cloud

      • KEY_ID: ID kunci yang ingin Anda batasi.

      curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      --data '{
      "restrictions" : {
      "iosKeyRestrictions": {
        "allowedBundleIds": ["ALLOWED_BUNDLE_ID_1","ALLOWED_BUNDLE_ID_2"]
      }
      }
      }' \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

    Untuk informasi selengkapnya tentang menambahkan pembatasan aplikasi iOS ke kunci menggunakan REST API, lihat Menambahkan pembatasan iOS dalam dokumentasi API Keys API.

    Menambahkan pembatasan API

    Pembatasan API menentukan API mana yang dapat dipanggil menggunakan kunci API.

    Untuk menambahkan pembatasan API, gunakan salah satu opsi berikut:

    Konsol

    1. Di konsol Google Cloud , buka halaman Credentials:

      Buka Kredensial

    2. Klik nama kunci API yang ingin Anda batasi.

    3. Di bagian API restrictions, klik Restrict key.

    4. Pilih semua API yang akan digunakan oleh kunci API Anda.

    5. Klik Simpan untuk menyimpan perubahan dan kembali ke daftar kunci API.

    gcloud

    1. Dapatkan ID kunci yang ingin Anda batasi.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list untuk mencantumkan kunci di project Anda.

    2. Gunakan perintah gcloud services api-keys update untuk menentukan layanan mana yang dapat menggunakan kunci API untuk mengakses.

      Ganti nilai berikut:

      • KEY_ID: ID kunci yang ingin Anda batasi.
      • SERVICE_1, SERVICE_2...: Nama layanan API yang dapat diakses menggunakan kunci.

        Anda harus memberikan semua nama layanan dengan perintah update; nama layanan yang diberikan menggantikan layanan yang ada pada kunci tersebut.

      Anda dapat menemukan nama layanan dengan menelusuri API di dasbor API. Nama layanan adalah string seperti bigquery.googleapis.com.

      gcloud services api-keys update KEY_ID \
      --api-target=service=SERVICE_1 --api-target=service=SERVICE_2

    Java

    Untuk menjalankan contoh ini, Anda harus menginstal library klien google-cloud-apikeys.

    
    import com.google.api.apikeys.v2.ApiKeysClient;
    import com.google.api.apikeys.v2.ApiTarget;
    import com.google.api.apikeys.v2.Key;
    import com.google.api.apikeys.v2.Restrictions;
    import com.google.api.apikeys.v2.UpdateKeyRequest;
    import com.google.protobuf.FieldMask;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class RestrictApiKeyApi {
    
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(Developer): Before running this sample,
        //  1. Replace the variable(s) below.
        String projectId = "GOOGLE_CLOUD_PROJECT_ID";
    
        // ID of the key to restrict. This ID is auto-created during key creation.
        // This is different from the key string. To obtain the key_id,
        // you can also use the lookup api: client.lookupKey()
        String keyId = "key_id";
    
        restrictApiKeyApi(projectId, keyId);
      }
    
      // Restricts an API key. Restrictions specify which APIs can be called using the API key.
      public static void restrictApiKeyApi(String projectId, String keyId)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the `apiKeysClient.close()` method on the client to safely
        // clean up any remaining background resources.
        try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
    
          // Restrict the API key usage by specifying the target service and methods.
          // The API key can only be used to authenticate the specified methods in the service.
          Restrictions restrictions = Restrictions.newBuilder()
              .addApiTargets(ApiTarget.newBuilder()
                  .setService("translate.googleapis.com")
                  .addMethods("translate.googleapis.com.TranslateText")
                  .build())
              .build();
    
          Key key = Key.newBuilder()
              .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
              // Set the restriction(s).
              // For more information on API key restriction, see:
              // https://cloud.google.com/docs/authentication/api-keys
              .setRestrictions(restrictions)
              .build();
    
          // Initialize request and set arguments.
          UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
              .setKey(key)
              .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
              .build();
    
          // Make the request and wait for the operation to complete.
          Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);
    
          // For authenticating with the API key, use the value in "result.getKeyString()".
          System.out.printf("Successfully updated the API key: %s", result.getName());
        }
      }
    }

    Python

    Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci API.

    
    from google.cloud import api_keys_v2
    from google.cloud.api_keys_v2 import Key
    
    
    def restrict_api_key_api(project_id: str, key_id: str) -> Key:
        """
        Restricts an API key. Restrictions specify which APIs can be called using the API key.
    
        TODO(Developer): Replace the variables before running the sample.
    
        Args:
            project_id: Google Cloud project id.
            key_id: ID of the key to restrict. This ID is auto-created during key creation.
                This is different from the key string. To obtain the key_id,
                you can also use the lookup api: client.lookup_key()
    
        Returns:
            response: Returns the updated API Key.
        """
    
        # Create the API Keys client.
        client = api_keys_v2.ApiKeysClient()
    
        # Restrict the API key usage by specifying the target service and methods.
        # The API key can only be used to authenticate the specified methods in the service.
        api_target = api_keys_v2.ApiTarget()
        api_target.service = "translate.googleapis.com"
        api_target.methods = ["transate.googleapis.com.TranslateText"]
    
        # Set the API restriction(s).
        # For more information on API key restriction, see:
        # https://cloud.google.com/docs/authentication/api-keys
        restrictions = api_keys_v2.Restrictions()
        restrictions.api_targets = [api_target]
    
        key = api_keys_v2.Key()
        key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
        key.restrictions = restrictions
    
        # Initialize request and set arguments.
        request = api_keys_v2.UpdateKeyRequest()
        request.key = key
        request.update_mask = "restrictions"
    
        # Make the request and wait for the operation to complete.
        response = client.update_key(request=request).result()
    
        print(f"Successfully updated the API key: {response.name}")
        # Use response.key_string to authenticate.
        return response
    
    

    REST

    1. Dapatkan ID kunci yang ingin Anda batasi.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini menggunakan metode keys.list. ID tercantum di kolom uid respons.

      Ganti PROJECT_ID dengan Google Cloud project ID atau nama project Anda.

      curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    2. Gunakan metode keys.patch untuk menentukan layanan mana yang dapat menggunakan kunci API untuk mengakses.

      Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mengetahui kapan operasi selesai dan mendapatkan status operasi.

      Ganti nilai berikut:

      • SERVICE_1, SERVICE_2...: Nama layanan API yang dapat diakses menggunakan kunci.

        Anda harus memasukkan semua nama layanan dalam permintaan; nama layanan yang diberikan menggantikan layanan yang ada pada kunci tersebut.

        Anda dapat menemukan nama layanan dengan menelusuri API di dasbor API. Nama layanan adalah string seperti bigquery.googleapis.com.

      • PROJECT_ID: Project ID atau nama project Anda. Google Cloud

      • KEY_ID: ID kunci yang ingin Anda batasi.

      curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      --data '{
      "restrictions" : {
      "apiTargets": [
        {
          "service": "SERVICE_1"
        },
        {
          "service" : "SERVICE_2"
        },
      ]
      }
      }' \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"

    Untuk informasi selengkapnya tentang menambahkan pembatasan API ke kunci menggunakan REST API, lihat Menambahkan pembatasan API dalam dokumentasi API Keys API.

    Mendapatkan informasi project dari string kunci

    Anda dapat menentukan project mana yang terkait dengan kunci API dari string-nya. Google Cloud

    Ganti KEY_STRING dengan string kunci yang informasi project Anda diperlukan.

    gcloud

    Gunakan perintah gcloud services api-keys lookup untuk mendapatkan project ID dari string kunci.

     gcloud services api-keys lookup KEY_STRING
     

    Java

    Untuk menjalankan contoh ini, Anda harus menginstal library klien google-cloud-apikeys.

    
    import com.google.api.apikeys.v2.ApiKeysClient;
    import com.google.api.apikeys.v2.LookupKeyRequest;
    import com.google.api.apikeys.v2.LookupKeyResponse;
    import java.io.IOException;
    
    public class LookupApiKey {
    
      public static void main(String[] args) throws IOException {
        // TODO(Developer): Before running this sample,
        //  1. Replace the variable(s) below.
        //  2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
        //  3. Make sure you have the necessary permission to view API keys.
        // API key string to retrieve the API key name.
        String apiKeyString = "API_KEY_STRING";
    
        lookupApiKey(apiKeyString);
      }
    
      // Retrieves name (full path) of an API key using the API key string.
      public static void lookupApiKey(String apiKeyString) throws IOException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the `apiKeysClient.close()` method on the client to safely
        // clean up any remaining background resources.
        try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
    
          // Initialize the lookup request and set the API key string.
          LookupKeyRequest lookupKeyRequest = LookupKeyRequest.newBuilder()
              .setKeyString(apiKeyString)
              .build();
    
          // Make the request and obtain the response.
          LookupKeyResponse response = apiKeysClient.lookupKey(lookupKeyRequest);
    
          System.out.printf("Successfully retrieved the API key name: %s", response.getName());
        }
      }
    }

    Python

    Untuk menjalankan contoh ini, Anda harus menginstal library klien Kunci API.

    
    from google.cloud import api_keys_v2
    
    
    def lookup_api_key(api_key_string: str) -> None:
        """
        Retrieves name (full path) of an API key using the API key string.
    
        TODO(Developer):
        1. Before running this sample,
          set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
        2. Make sure you have the necessary permission to view API keys.
    
        Args:
            api_key_string: API key string to retrieve the API key name.
        """
    
        # Create the API Keys client.
        client = api_keys_v2.ApiKeysClient()
    
        # Initialize the lookup request and set the API key string.
        lookup_key_request = api_keys_v2.LookupKeyRequest(
            key_string=api_key_string,
            # Optionally, you can also set the etag (version).
            # etag=etag,
        )
    
        # Make the request and obtain the response.
        lookup_key_response = client.lookup_key(lookup_key_request)
    
        print(f"Successfully retrieved the API key name: {lookup_key_response.name}")
    
    

    REST

    Gunakan metode lookupKey untuk mendapatkan project ID dari string kunci.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://apikeys.googleapis.com/v2/keys:lookupKey?keyString=KEY_STRING"

    Membuat salinan kunci API

    Jika Anda memerlukan kunci API baru dengan batasan yang sama seperti kunci API yang ada, Anda dapat membuat salinan kunci API yang ada. Operasi ini membuat kunci API baru dengan string dan ID kunci yang unik, dengan pembatasan kunci API yang ada.

    Operasi penyalinan hanya tersedia di konsol Google Cloud . Untuk menggunakan metode lain, ikuti langkah-langkah untuk membuat kunci API, lalu terapkan pembatasan kunci API yang sama ke kunci API yang baru dibuat.

    1. Di konsol Google Cloud , buka halaman Credentials:

      Buka Kredensial

    2. Klik nama kunci API yang ingin Anda salin.

      Halaman detail kunci API akan terbuka.

    3. Klik Buat salinan.

    4. Masukkan nama untuk kunci API baru dan konfirmasi bahwa pembatasannya sudah benar.

    5. Klik Buat.

    Merotasi kunci API

    Dengan mengganti kunci API secara berkala, Anda dapat membatasi dampak dari kunci API yang disusupi.

    Saat merotasi kunci API, Anda membuat kunci baru dengan batasan yang sama seperti kunci lama, dan mengupdate aplikasi Anda untuk menggunakan kunci baru. Setelah semua aplikasi Anda diupdate, Anda dapat menghapus kunci lama.

    Operasi rotasi hanya tersedia di konsol Google Cloud . Untuk menggunakan metode lain, ikuti langkah-langkah untuk membuat kunci API, lalu terapkan pembatasan kunci API yang sama ke kunci API yang baru dibuat. Setelah mengupdate aplikasi untuk menggunakan kunci baru, Anda menghapus kunci lama.

    1. Di konsol Google Cloud , buka halaman Credentials:

      Buka Kredensial

    2. Klik nama kunci API yang ingin Anda ganti untuk membuka halaman detailnya.

    3. Klik Rotate key.

    4. Masukkan nama untuk kunci API baru dan konfirmasi bahwa pembatasannya sudah benar.

    5. Klik Buat.

    6. Salin string kunci dan perbarui aplikasi Anda agar menggunakan string baru.

    7. Setelah Anda mengupdate semua aplikasi untuk menggunakan kunci baru, kembali ke halaman detail untuk kunci baru. Di bagian Kunci sebelumnya, klik Hapus kunci sebelumnya untuk menghapus kunci lama.

      Jika Anda mendapati bahwa Anda menghapus kunci lama sebelum waktunya, Anda dapat membatalkan penghapusannya.

    Membatalkan Penghapusan kunci API

    Jika tidak sengaja menghapus kunci API, Anda dapat membatalkan penghapusan (memulihkan) kunci tersebut dalam waktu 30 hari setelah menghapus kunci. Setelah 30 hari, Anda tidak dapat membatalkan penghapusan kunci API.

    Konsol

    1. Di konsol Google Cloud , buka halaman Credentials:

      Buka Kredensial

    2. Klik Restore deleted credentials.

    3. Temukan kunci API yang dihapus yang ingin Anda batalkan penghapusannya, lalu klik Restore.

      Membatalkan penghapusan kunci API mungkin memerlukan waktu beberapa menit untuk diterapkan. Setelah penerapan, kunci API yang batal dihapus akan ditampilkan di daftar kunci API.

    gcloud

    1. Dapatkan ID kunci yang ingin Anda batalkan penghapusannya.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list --show-deleted untuk mencantumkan kunci yang dihapus di project Anda.

    2. Gunakan perintah gcloud services api-keys undelete untuk membatalkan penghapusan kunci API.

      gcloud services api-keys undelete KEY_ID

      Ganti nilai berikut:

      • KEY_ID: ID kunci yang ingin Anda batalkan penghapusannya.

    Java

    Untuk menjalankan contoh ini, Anda harus menginstal library klien google-cloud-apikeys.

    import com.google.api.apikeys.v2.ApiKeysClient;
    import com.google.api.apikeys.v2.Key;
    import com.google.api.apikeys.v2.UndeleteKeyRequest;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class UndeleteApiKey {
    
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(developer): Replace these variables before running the sample.
        // Project ID or project number of the Google Cloud project.
        String projectId = "YOUR_PROJECT_ID";
        // The API key id to undelete.
        String keyId = "YOUR_KEY_ID";
    
        undeleteApiKey(projectId, keyId);
      }
    
      // Undeletes an API key.
      public static void undeleteApiKey(String projectId, String keyId)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {
    
          // Initialize the undelete request and set the argument.
          UndeleteKeyRequest undeleteKeyRequest = UndeleteKeyRequest.newBuilder()
              .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
              .build();
    
          // Make the request and wait for the operation to complete.
          Key undeletedKey = apiKeysClient.undeleteKeyAsync(undeleteKeyRequest)
              .get(3, TimeUnit.MINUTES);
    
          System.out.printf("Successfully undeleted the API key: %s", undeletedKey.getName());
        }
      }
    }

    REST

    1. Dapatkan ID kunci yang ingin Anda batalkan penghapusannya.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini menggunakan metode keys.list, dengan parameter kueri showDeleted ditetapkan ke true. ID kunci tercantum di kolom uid respons.

      Ganti PROJECT_ID dengan Google Cloud project ID atau nama project Anda.

      curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys?showDeleted=true"
    2. Gunakan metode undelete untuk membatalkan penghapusan kunci API.

      curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json; charset=utf-8" \
      "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID:undelete"

      Permintaan ini menampilkan operasi yang berjalan lama; Anda harus melakukan polling operasi untuk mengetahui kapan operasi selesai dan mendapatkan status operasi.

      Ganti nilai berikut:

      • PROJECT_ID: Project ID atau nama project Anda. Google Cloud
      • KEY_ID: ID kunci yang ingin Anda batasi.

    Menentukan jenis kunci API

    Anda dapat menentukan apakah kunci API terikat ke akun layanan dengan memeriksa kunci tersebut.

    Konsol

    1. Di konsol Google Cloud , buka halaman Credentials:

      Buka Kredensial

      Jika kunci API terikat ke akun layanan, ID akun layanan akan ditampilkan.

    gcloud

    1. Dapatkan ID kunci.

      ID tidak sama dengan nama tampilan atau string kunci. Anda bisa mendapatkan ID ini dengan menggunakan perintah gcloud services api-keys list untuk mencantumkan kunci di project Anda.

    2. Gunakan perintah gcloud services api-keys describe untuk mendeskripsikan kunci API.

      gcloud services api-keys describe KEY_ID

      Jika kunci API terikat ke akun layanan, kolom serviceAccountEmail akan ditampilkan.

    Melakukan polling operasi yang berjalan lama

    Metode API Keys API menggunakan operasi yang berjalan lama. Jika Anda menggunakan REST API untuk membuat dan mengelola kunci API, objek operasi akan ditampilkan dari permintaan metode awal. Anda menggunakan nama operasi untuk mengumpulkan operasi yang berjalan lama. Setelah permintaan yang berjalan lama selesai, polling operasi akan menampilkan data dari permintaan yang berjalan lama.

    Untuk melakukan polling operasi API Keys API yang berjalan lama, gunakan metode operations.get.

    Ganti OPERATION_NAME dengan nama operasi yang ditampilkan oleh operasi yang berjalan lama. Contoh, operations/akmf.p7-358517206116-cd10a88a-7740-4403-a8fd-979f3bd7fe1c.

    curl -X GET \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "Content-Type: application/json; charset=utf-8" \
        "https://apikeys.googleapis.com/v2/OPERATION_NAME"

    Batasan pada kunci API

    Anda dapat membuat hingga 300 kunci API per project. Batas ini adalah batas sistem, dan tidak dapat diubah menggunakan permintaan penambahan kuota. Jika diperlukan lebih dari satu kunci API, Anda harus menggunakan lebih dari satu project.

    Anda dapat menambahkan hingga 1200 pembatasan aplikasi ke kunci API.

    Langkah berikutnya