Category
Application development
1. Introduction
API Keys API is the Google Cloud service that lets you create, list, update, restrict, rotate, and delete API keys programmatically.
In simple terms: it helps you manage API keys the same way you manage other cloud resources—through automation, IAM, audit logs, and repeatable workflows—instead of relying only on manual Console clicks.
Technically, API Keys API is a control-plane API (apikeys.googleapis.com) that provides a resource model for API keys within a Google Cloud project (for example: projects/{project}/locations/global/keys/{key}). It integrates with Google Cloud IAM for authorization, Cloud Audit Logs for auditing, and Service Usage / API Library for enabling the APIs that keys can call. The keys you create can then be used by clients to authenticate to Google APIs that accept API keys (for example, certain Google APIs accessed via ?key=...).
The problem it solves: teams need a secure, auditable, scalable way to manage API keys across environments (dev/test/prod), across many applications, and across many developers—without hard-to-review manual changes, uncontrolled key sprawl, or weak restrictions.
Service naming note: “API Keys API” is the current official service name in Google Cloud’s API Library. The Console experience under APIs & Services → Credentials is the UI on top of the same API-key management capabilities. The tutorial below focuses on the API Keys API specifically (automation and API-driven operations), while also referencing the Console when it is the most reliable way to discover certain values.
2. What is API Keys API?
Official purpose
API Keys API is the Google Cloud API for managing API keys as first-class resources. It enables you to programmatically:
- Create and delete API keys
- List and get API key metadata
- Update API key properties (for example, display name and restrictions)
- Retrieve the actual key string when needed (treat as sensitive)
- Apply and manage restrictions to reduce misuse
Official docs: https://cloud.google.com/api-keys/docs
Core capabilities
- Lifecycle management: create, list, patch/update, delete
- Restrictions management:
- Application restrictions (for example, HTTP referrers, IP addresses, Android apps, iOS apps)
- API restrictions (limit which enabled APIs the key can call)
- Automation support: integrate into CI/CD and infrastructure workflows
- Governance: IAM permissions, audit logging, and quotas
Major components
- API Keys API endpoint:
apikeys.googleapis.com - Key resource: stored under a project, in location
global - Long-running operations: create/update/delete actions typically return an operation you poll until completion
- IAM roles & permissions: control who can manage keys and who can retrieve key strings
Service type
- Control-plane management API (resource management), not a data-plane runtime.
- You do not “deploy” API Keys API; you enable it in a Google Cloud project and call it via REST/gRPC/clients.
Scope (project/regional/etc.)
- Project-scoped: keys belong to a Google Cloud project.
- Location: currently modeled as
locations/global(global resource namespace within the project). - Not zonal/regional compute: no VPC attachment and no compute footprint.
How it fits into the Google Cloud ecosystem
API Keys API sits in the Application development layer as a foundational building block for:
- Managing access to Google APIs that accept API keys
- Enforcing restrictions that reduce unintended usage and cost exposure
- Enabling safe automation alongside:
- IAM (authorization for key management)
- Cloud Audit Logs (tracking key changes)
- Service Usage / API Library (enabling the APIs your key can call)
- Secret Manager (storing server-side keys safely)
- Cloud Monitoring / Logging (operational visibility, mostly through consumer APIs and audit logs)
3. Why use API Keys API?
Business reasons
- Reduce risk of unexpected bills: keys can be restricted to specific APIs and clients.
- Speed up delivery: teams can self-serve key creation and rotation via automation.
- Standardize governance: consistent naming, labeling (where applicable), and lifecycle rules across many teams/projects.
Technical reasons
- Infrastructure as Code patterns: while API keys aren’t always a perfect IaC fit (because the key string is sensitive), API Keys API enables controlled automation and repeatability.
- Integrate with CI/CD: create or rotate keys during deployments, and update downstream configuration safely.
- Programmatic restrictions: reduce manual configuration drift.
Operational reasons
- Auditability: changes to keys can be tracked in Cloud Audit Logs.
- Scalability: manage hundreds/thousands of keys across projects without Console-only processes.
- Standard lifecycle: automated rotation schedules and cleanup for unused keys.
Security/compliance reasons
- Least privilege: IAM roles limit who can create/update/delete keys and who can retrieve key strings.
- Restrict where keys can be used: referrer/IP/app restrictions reduce key theft impact.
- Separation of duties: different roles for creating keys vs. deploying apps vs. security review.
Scalability/performance reasons
- The management API scales for large organizations (within quotas).
- Client-side performance depends on the Google APIs being called; API Keys API itself is not on the runtime path of your application.
When teams should choose it
Choose API Keys API when you need one or more of: – Automation for creating/restricting/rotating API keys – Auditable governance and controlled access to key strings – Standardized key management across multiple applications/environments
When teams should not choose it
API keys are not a substitute for strong identity: – If the target API supports and requires OAuth 2.0, service accounts, Workload Identity Federation, or mTLS, prefer those for robust authentication. – If you need user-level authorization, fine-grained access control, or non-repudiation, API keys are usually the wrong tool. – If the API does not support API keys, API Keys API won’t help—use the correct auth method.
4. Where is API Keys API used?
Industries
- SaaS and software companies consuming Google APIs
- Media/streaming and analytics (YouTube Data API usage patterns)
- Retail and logistics (Maps APIs—note cost sensitivity)
- Education and research (public Google APIs usage)
- Fintech and regulated orgs (where governance and audit are required)
Team types
- Platform engineering teams building shared developer tooling
- DevOps/SRE teams implementing secure CI/CD and secrets workflows
- Security engineering teams enforcing guardrails for API consumption
- Application development teams integrating Google APIs into apps
Workloads
- Web apps calling Google APIs from browser or backend
- Mobile apps using Google APIs (Android/iOS restrictions)
- Server-to-server workloads where API keys are still used (less ideal than service accounts, but sometimes required for specific APIs)
Architectures
- Multi-project environments (dev/test/prod separation)
- Multi-tenant SaaS platforms with separate keys per customer or per environment
- Microservices that call Google APIs and require compartmentalized keys
Real-world deployment contexts
- Centralized key management in a shared platform project
- Keys per application, per environment, and per client type (browser vs server vs mobile)
- Key rotation pipelines integrated into release processes
Production vs dev/test usage
- Dev/test: quick key creation for experimentation, but still enforce restrictions to prevent accidental exposure.
- Production: strict restrictions, tight IAM, audit review, rotation, and monitoring of usage and errors.
5. Top Use Cases and Scenarios
Below are realistic, common scenarios for API Keys API in Google Cloud.
1) Automated API key provisioning for CI/CD
- Problem: Manual key creation causes delays and inconsistency between environments.
- Why API Keys API fits: Programmatic creation and updates align with pipeline automation.
- Example: A deployment pipeline creates a new key for
staging, stores it in Secret Manager, and updates a Cloud Run service.
2) API key rotation with minimal downtime
- Problem: Long-lived keys increase risk; rotating manually is error-prone.
- Why it fits: Create new key, update consumers, then delete old key in an automated flow.
- Example: A weekly job rotates keys used by a backend integration with a Google API.
3) Enforcing “API restrictions” to prevent misuse
- Problem: A leaked key can be used against any enabled API, increasing blast radius.
- Why it fits: Restrict a key to specific APIs only.
- Example: A key used for YouTube Data API is restricted so it cannot call other Google APIs.
4) Enforcing HTTP referrer restrictions for browser keys
- Problem: Browser-exposed keys get scraped and reused from unauthorized sites.
- Why it fits: Restrict usage to allowed referrer patterns.
- Example: Only requests from
https://app.example.com/*can use the key.
5) Enforcing IP restrictions for server-to-server keys
- Problem: Backend keys are stolen and abused from unknown servers.
- Why it fits: Restrict by source IP ranges (when your egress IPs are stable).
- Example: Only NAT gateway IPs of a production VPC can use the key.
6) Standardized key naming and inventory at scale
- Problem: Large orgs lose track of which key belongs to which app/team.
- Why it fits: Programmatically list keys and enforce naming conventions.
- Example: A nightly inventory job checks that all keys follow
env-app-ownerpattern.
7) Controlled developer self-service with guardrails
- Problem: Developers need keys quickly, but security needs oversight.
- Why it fits: IAM allows limited roles; automation can apply baseline restrictions.
- Example: Developers can create keys but cannot retrieve key strings; a secure process retrieves/stores them.
8) Multi-environment separation (dev/test/prod)
- Problem: Using the same key across environments increases risk and makes incident response harder.
- Why it fits: Different projects or different keys per environment; manage programmatically.
- Example: Separate keys for
dev,staging,prodwith different restrictions and quotas.
9) Incident response: revoke leaked key quickly
- Problem: A key is found in a public repository; need immediate containment.
- Why it fits: Delete the key quickly via API; automation can react to detections.
- Example: A security workflow triggers deletion when a secret scanner flags a key.
10) Migrating from “unrestricted keys” to restricted keys
- Problem: Legacy projects have many unrestricted keys.
- Why it fits: Bulk list keys, identify unrestricted ones, and patch restrictions.
- Example: A migration script updates keys to add API restrictions and IP restrictions.
11) Central platform team managing keys for multiple apps
- Problem: Inconsistent key handling across app teams.
- Why it fits: Centralized automation using API Keys API with IAM.
- Example: A platform service offers an internal “key request” endpoint that creates keys with org-approved restrictions.
12) Compliance reporting and audit readiness
- Problem: Auditors ask who created keys, when, and what restrictions exist.
- Why it fits: Audit logs + programmatic reporting from key metadata.
- Example: Monthly report lists keys, owners, restrictions, and last modification.
6. Core Features
Note: Feature availability and exact field names can evolve. For the most current API surface, verify in official docs: https://cloud.google.com/api-keys/docs and the API reference.
Feature 1: Create and manage API keys as resources
- What it does: Create, list, get, update, and delete keys in a project.
- Why it matters: Keys become governed cloud resources with IAM controls and auditing.
- Practical benefit: Automation at scale; less manual Console work.
- Caveats: Create/update/delete often uses long-running operations; build polling into automation.
Feature 2: Retrieve the key string (sensitive)
- What it does: Provides a way to programmatically retrieve the actual secret key string for use by applications.
- Why it matters: Many workflows need the value to deploy into runtime config or secrets storage.
- Practical benefit: Enables secure delivery pipelines (retrieve → store in Secret Manager → deploy).
- Caveats: Treat the key string like a secret. Restrict who can retrieve it via IAM. Avoid logging it.
Feature 3: Application restrictions
- What it does: Restrict where a key can be used, such as:
- HTTP referrers (browser usage)
- IP addresses (server usage with stable egress IPs)
- Android apps (package name + SHA-1 cert fingerprint)
- iOS apps (bundle identifier)
- Why it matters: Reduces blast radius if a key is exposed.
- Practical benefit: A stolen key used from elsewhere fails authorization.
- Caveats: Some restriction types are specific to certain APIs and client types. IP restrictions require stable egress IPs (often NAT). Browser referrer restrictions can be bypassed in some scenarios; do not rely on them as the only protection.
Feature 4: API restrictions (limit enabled APIs the key can call)
- What it does: Restrict the key to calling only specified APIs.
- Why it matters: Prevents misuse against other enabled APIs in the project.
- Practical benefit: Even if leaked, the key can’t be used broadly.
- Caveats: You must specify the correct service identifiers. Discover service names via API Library or
gcloud services list --enabled. Always test after applying restrictions.
Feature 5: Integration with IAM (authorization)
- What it does: Use IAM roles/permissions to control who can manage keys and retrieve key strings.
- Why it matters: Prevents uncontrolled key creation and secret exposure.
- Practical benefit: Apply least privilege and separation of duties.
- Caveats: Ensure you understand which role grants ability to retrieve key strings; limit it to a small set of identities.
Feature 6: Cloud Audit Logs integration
- What it does: Records administrative actions (create/update/delete keys) and access patterns where applicable.
- Why it matters: Provides traceability for compliance and incident response.
- Practical benefit: You can answer “who changed what and when” for keys.
- Caveats: Audit log retention and sinks are your responsibility. Verify which log types are generated for key-string access in your environment.
Feature 7: Quotas and rate limits for management operations
- What it does: Applies quotas to protect the service and your project from abuse.
- Why it matters: Encourages safe automation patterns (batching, backoff, caching).
- Practical benefit: Prevents a misbehaving script from creating/deleting large numbers of keys quickly.
- Caveats: Quotas vary; confirm in Google Cloud Console under IAM & Admin → Quotas or the API’s quota page.
7. Architecture and How It Works
High-level architecture
API Keys API is a management/control API. Your automation (human or pipeline) calls API Keys API to manage key resources. Applications then use the key to call a Google API that accepts API keys.
Request/data/control flow
- An admin or CI/CD pipeline authenticates to Google Cloud (usually OAuth 2.0) and calls API Keys API to create/update/delete a key.
- The create/update call returns a long-running operation.
- Once complete, the pipeline retrieves the key string and stores it securely (for server-side usage, typically Secret Manager).
- Client applications use the key when calling supported Google APIs (often as
?key=...or in headers, depending on API). - Google’s API gateway enforces key validity and restrictions (API restrictions and application restrictions).
Integrations with related services
- Service Usage / API Library: the APIs you call with the key must be enabled in the project.
- IAM: controls who can manage keys and access sensitive key material.
- Cloud Audit Logs: tracks key lifecycle actions.
- Secret Manager: recommended for storing server-side keys and distributing them to workloads.
- Cloud Build / CI systems: common automation runtimes for rotation and provisioning.
- Cloud Logging / Monitoring: observe errors, usage patterns, and build alerting (often via the consumer API’s logs/metrics plus audit logs for key changes).
Dependency services
- A Google Cloud project with billing configured (billing is not necessarily required for the API Keys API itself, but many consumer APIs require billing).
- Enabled APIs:
- API Keys API itself (
apikeys.googleapis.com) - Any target Google APIs you plan to call using the key
Security/authentication model
- For managing keys (control plane): Use OAuth 2.0 identities (human user, service account) authorized by IAM.
- For using keys (data plane): The API key string is presented to the target Google API; the key is not an IAM identity.
Networking model
- API Keys API is accessed over the public internet via HTTPS.
- You can call it from Cloud Shell, CI runners, on-prem, or other clouds.
- VPC-level private connectivity is not typically part of API Keys API usage; if you require private access patterns, review Google Cloud networking options and verify applicability for the specific APIs.
Monitoring/logging/governance considerations
- Enable and review Cloud Audit Logs for API Keys API admin activity.
- Build inventory reports: list keys, check restrictions, check age, rotate.
- Track consumer API usage and errors to detect abuse.
- Use organization policies and project structure to reduce blast radius.
Simple architecture diagram (conceptual)
flowchart LR
Dev[Developer / CI Pipeline] -->|OAuth 2.0 + IAM| AK[API Keys API<br/>apikeys.googleapis.com]
AK -->|Create/Update/Delete key| Keys[(API Key resource<br/>in Project)]
Dev -->|Store key string| SM[Secret Manager]
App[Application] -->|API key| GoogleAPI[Google API that accepts API keys]
GoogleAPI -->|Enforces restrictions| App
Production-style architecture diagram (with governance)
flowchart TB
subgraph Org[Google Cloud Organization]
subgraph ProdProject[Prod Project]
AK[API Keys API]
Audit[Cloud Audit Logs]
SM[Secret Manager]
API1[Enabled Google APIs]
end
subgraph SecProject[Security Project]
LogSink[Log Sink]
SIEM[SIEM / SecOps]
end
end
subgraph CICD[CI/CD]
CB[Cloud Build or External CI Runner]
end
subgraph Runtime[Runtime]
CR[Cloud Run / GKE / Compute]
end
CB -->|OAuth + IAM| AK
AK --> Audit
Audit -->|Export| LogSink --> SIEM
CB -->|Retrieve key string| AK
CB -->|Write secret version| SM
CR -->|Access secret| SM
CR -->|Call API with key| API1
8. Prerequisites
Account/project requirements
- A Google Cloud account with access to a project.
- A Google Cloud project where you can enable APIs and create credentials.
Permissions / IAM roles
You need IAM permissions to: – Enable APIs (typically Project Owner/Editor, or specific Service Usage Admin permissions) – Manage API keys (create/update/delete/list/get) – Retrieve key strings (sensitive permission)
Google Cloud provides predefined roles for API Keys API (for example, “API Keys Admin” and “API Keys Viewer” in many environments). Verify the exact role IDs and which permissions include key-string retrieval in official docs: – https://cloud.google.com/api-keys/docs
If you’re in a locked-down environment, ask for: – The minimal IAM permissions to create/update keys – A separate, tightly controlled permission set for retrieving key strings
Billing requirements
- API Keys API management operations are generally not a direct billing driver, but many Google APIs you call using API keys are billable (e.g., Maps).
- If your chosen target API requires billing, ensure the project is linked to a billing account.
CLI/SDK/tools needed
- Cloud Shell (recommended) or local setup with:
gcloudCLI authenticated to your projectcurljq(optional but helpful)- If scripting: bash, PowerShell, or Python
Region availability
- API key resources are modeled under
locations/global. - Availability is generally global for management, but verify any organization policy constraints.
Quotas/limits
- API Keys API has quotas on management requests and may have limits on number of keys per project.
- Check quotas in the Console:
- IAM & Admin → Quotas (filter by “API Keys API”), or the API’s quota page.
- Also account for quotas of the Google APIs your application will call using the key.
Prerequisite services
- Enable API Keys API in the project:
apikeys.googleapis.com- Enable at least one API that accepts API keys (for the hands-on lab). The tutorial uses a Google API example; you can choose another API if preferred.
9. Pricing / Cost
Current pricing model (accurate framing)
- API Keys API is a management/control API. Google Cloud typically does not bill separately for “creating credentials” operations, but billing models can change.
- The major cost impact comes from the APIs that are called using the API key, not from the act of managing keys.
Because pricing and SKUs vary by API, region, and usage volume: – For API Keys API pricing specifics: Verify in official docs and pricing pages. – For the API you intend to call (for example Maps, YouTube, etc.), consult that API’s pricing page.
Useful starting points: – Google Cloud pricing overview: https://cloud.google.com/pricing – Pricing calculator: https://cloud.google.com/products/calculator
Pricing dimensions (what actually drives cost)
- Consumer API usage (primary driver) – Requests per day/month – Data processed (depends on API) – Premium features (depends on API)
- Quota overages or paid tiers (depends on API)
- Networking egress – If your workload runs outside Google Cloud or crosses regions, outbound egress may apply.
- Secret storage and access (if using Secret Manager) – Secret versions stored – Secret access operations
- Logging – Log ingestion and retention if you export/retain large volumes of logs
Free tier (if applicable)
- Many Google APIs have free quotas; some are purely quota-based (like certain public APIs), while others are strictly paid (like many Maps APIs).
- Verify the free tier for your chosen API. API Keys API itself does not typically have a “free tier” concept; it’s governed by quotas.
Hidden or indirect costs to plan for
- Accidental exposure of unrestricted keys can create large unplanned bills (especially for billable APIs).
- Rotation automation can increase Secret Manager versions and access operations.
- Excessive logging (especially exporting logs to SIEM) can become a cost driver.
How to optimize cost
- Restrict keys to:
- Only the APIs they need (API restrictions)
- Only the client types they need (referrer/IP/app restrictions)
- Use separate projects for dev/test/prod to isolate blast radius.
- Use budget alerts and monitoring on the consumer APIs.
- Rotate and delete unused keys to reduce risk.
- For server-to-server on Google Cloud, prefer IAM-based auth where supported (service accounts) over API keys.
Example low-cost starter estimate (model, not fabricated numbers)
A starter setup might include: – 1–3 API keys in a dev project – 1 enabled Google API with a free quota – Minimal Secret Manager usage (or none if testing locally)
Cost behavior: – Likely near-zero if the target API has free quotas and you stay within them. – Costs can increase if you enable billable APIs or exceed free quotas.
Example production cost considerations
In production, plan for: – API consumption costs of your target APIs (primary) – Key segmentation by environment and application – Secret Manager usage at scale – Log export and SIEM ingestion – Incident response overhead (not a cloud bill line item, but real cost)
10. Step-by-Step Hands-On Tutorial
This lab is designed to be safe and low-cost by: – Using Cloud Shell for tooling (no local setup required) – Demonstrating key creation and retrieval via API Keys API – Demonstrating a real API call using the key – Optionally applying restrictions (with clear verification guidance)
Objective
- Enable API Keys API
- Create an API key using API Keys API (REST)
- Retrieve the key string securely
- Use the key to call a Google API that accepts API keys
- (Optional) Apply restrictions and validate behavior
- Clean up by deleting the key
Lab Overview
You will: 1. Set project variables in Cloud Shell 2. Enable required APIs 3. Create an API key via API Keys API 4. Poll the operation until completion 5. Retrieve the key string 6. Make a test request using the API key 7. Optionally restrict the key to specific APIs 8. Delete the key
Step 1: Open Cloud Shell and set your project
- In the Google Cloud Console, open Cloud Shell.
- Set your project:
gcloud config set project YOUR_PROJECT_ID
- Confirm the active project:
gcloud config get-value project
Expected outcome: Your Cloud Shell session is targeting the intended project.
- Capture your project number (needed for API Keys API resource paths):
PROJECT_ID="$(gcloud config get-value project)"
PROJECT_NUMBER="$(gcloud projects describe "$PROJECT_ID" --format="value(projectNumber)")"
echo "PROJECT_ID=$PROJECT_ID"
echo "PROJECT_NUMBER=$PROJECT_NUMBER"
Expected outcome: You see both PROJECT_ID and PROJECT_NUMBER.
Step 2: Enable API Keys API (and a test API)
Enable API Keys API:
gcloud services enable apikeys.googleapis.com
Choose a Google API that accepts API keys for testing. One common option is a Google API reachable via www.googleapis.com endpoints.
For example, you can enable YouTube Data API v3 (often used with API keys). Service names can vary by API; confirm in API Library if needed.
Try enabling:
gcloud services enable youtube.googleapis.com
If that fails because the service name differs in your environment, do this instead: – Go to APIs & Services → Library – Search for the API you want (e.g., “YouTube Data API v3”) – Enable it, then return to Cloud Shell
To list enabled services and find the correct identifier:
gcloud services list --enabled --format="table(name,title)"
Expected outcome: apikeys.googleapis.com is enabled, and at least one consumer API is enabled for testing.
Step 3: Create an API key using API Keys API (REST)
- Create a unique key ID (must be unique per project) and a display name:
KEY_ID="lab-key-$(date +%Y%m%d%H%M%S)"
DISPLAY_NAME="API Keys API lab key"
echo "KEY_ID=$KEY_ID"
- Get an access token for calling Google Cloud APIs:
ACCESS_TOKEN="$(gcloud auth print-access-token)"
- Call API Keys API to create the key.
API Keys API uses locations/global. Create the key:
CREATE_RESP="$(
curl -sS -X POST \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
"https://apikeys.googleapis.com/v2/projects/${PROJECT_NUMBER}/locations/global/keys?keyId=${KEY_ID}" \
-d "{
\"displayName\": \"${DISPLAY_NAME}\"
}"
)"
echo "$CREATE_RESP" | sed 's/./&/g' >/dev/null
echo "$CREATE_RESP" | head -c 2000; echo
You should receive a response representing a long-running operation, including an operation name.
Extract the operation name (requires jq; Cloud Shell commonly has it. If not, install or parse manually):
OP_NAME="$(echo "$CREATE_RESP" | jq -r '.name')"
echo "OP_NAME=$OP_NAME"
Expected outcome: You have an operation name like projects/.../locations/global/operations/....
Step 4: Poll the operation until it completes
Poll:
while true; do
ACCESS_TOKEN="$(gcloud auth print-access-token)"
OP_RESP="$(curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" "https://apikeys.googleapis.com/v2/${OP_NAME}")"
DONE="$(echo "$OP_RESP" | jq -r '.done')"
echo "done=$DONE"
if [ "$DONE" = "true" ]; then
echo "$OP_RESP" | jq .
break
fi
sleep 2
done
When done, the response should include the created key resource in response.
Extract the key resource name:
KEY_RESOURCE="$(echo "$OP_RESP" | jq -r '.response.name')"
echo "KEY_RESOURCE=$KEY_RESOURCE"
Expected outcome: You have a key resource name like projects/PROJECT_NUMBER/locations/global/keys/KEY_ID_OR_SYSTEM_ID.
Step 5: Retrieve the key string (treat as sensitive)
Retrieve the key string using the API’s method for getting the key string.
ACCESS_TOKEN="$(gcloud auth print-access-token)"
KEYSTRING_RESP="$(
curl -sS -H "Authorization: Bearer ${ACCESS_TOKEN}" \
"https://apikeys.googleapis.com/v2/${KEY_RESOURCE}/keyString"
)"
echo "$KEYSTRING_RESP" | jq .
Extract the key string:
API_KEY_STRING="$(echo "$KEYSTRING_RESP" | jq -r '.keyString')"
echo "API_KEY_STRING=${API_KEY_STRING}"
Expected outcome: You obtain an API key string. Do not paste it into tickets, logs, or chat.
If you want to avoid echoing it back in your terminal history, store it in an environment variable and do not print it.
Step 6: Use the API key to call an enabled API
Now call a Google API endpoint that accepts API keys.
For YouTube Data API (example), you can perform a basic search request:
curl -sS \
"https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&maxResults=1&q=google%20cloud&key=${API_KEY_STRING}" \
| head -c 2000; echo
Expected outcome: A JSON response with search results (or an error message explaining missing API enablement, quota, or configuration).
If you chose a different API, consult that API’s docs for the correct request format and where to include the key (query string or header).
Step 7 (Optional): Add API restrictions to reduce blast radius
API restrictions are one of the most important security controls for API keys.
There are two practical ways to apply them:
Option A: Apply restrictions in the Console (lowest risk of mis-typing service identifiers)
- Go to APIs & Services → Credentials
- Click your key
- Under API restrictions, choose Restrict key
- Select the specific API(s) (e.g., “YouTube Data API v3”)
- Save
Expected outcome: The key is only authorized for the selected APIs.
Option B: Apply restrictions via API Keys API (automation path)
This requires the correct service identifiers for the APIs you want to allow. To discover service names: – Use APIs & Services → Enabled APIs & services – Or run:
gcloud services list --enabled --format="value(name)"
Then patch the key with a restrictions update. The exact field structure must match the API reference; verify in official docs if fields differ: – https://cloud.google.com/api-keys/docs/reference/rest
A typical patch workflow:
1. Build a JSON body with restrictions.apiTargets.
2. Call PATCH with an updateMask that includes restrictions.
Example structure (you must replace ALLOWED_SERVICE_NAME with the correct enabled service name, e.g., from gcloud services list --enabled):
ALLOWED_SERVICE_NAME="youtube.googleapis.com" # verify
ACCESS_TOKEN="$(gcloud auth print-access-token)"
curl -sS -X PATCH \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
"https://apikeys.googleapis.com/v2/${KEY_RESOURCE}?updateMask=restrictions" \
-d "{
\"restrictions\": {
\"apiTargets\": [
{ \"service\": \"${ALLOWED_SERVICE_NAME}\" }
]
}
}" | jq .
Because updates can also be long-running operations in some cases, be prepared to poll an operation if the API returns one.
Expected outcome: The key metadata now shows API restrictions.
Step 8: (Optional) Validate restriction behavior
After restricting the key to only one API: – A call to the allowed API should succeed. – A call to a different API using the same key should fail with an authorization error.
For a quick sanity check: 1. Repeat your allowed API call (e.g., YouTube search). It should still succeed. 2. Call a different enabled API that accepts API keys (choose one you have enabled), and confirm it fails.
Expected outcome: Unauthorized calls are rejected.
Validation
Run these checks:
-
List keys using API Keys API (basic inventory): – You can use the API reference to list keys (verify the exact endpoint in docs). – Or confirm in Console under APIs & Services → Credentials.
-
Confirm the key works against the intended API: – Your test request returns a successful JSON response.
-
Confirm cleanup readiness: – You know the
KEY_RESOURCEname for deletion.
Troubleshooting
Error: PERMISSION_DENIED when calling API Keys API
- Cause: Your identity lacks API Keys API permissions.
- Fix:
- Ask for the appropriate IAM role(s) (API keys admin role) on the project.
- Confirm you’re operating in the correct project.
Error: 403 SERVICE_DISABLED
- Cause: The API you are calling (API Keys API or the consumer API) is not enabled.
- Fix:
- Enable the API in APIs & Services → Library or via
gcloud services enable ....
Error: INVALID_ARGUMENT for keyId
- Cause: Key ID does not meet naming rules or is already taken.
- Fix:
- Choose a different
KEY_ID(use timestamp suffix). - Verify API’s naming constraints in the reference docs.
Error: Consumer API returns API key not valid or not authorized
- Cause:
- Key restrictions block the request (expected if misconfigured).
- The API is not enabled in the project.
- The consumer API requires additional configuration (for example, a specific quota project or account settings).
- Fix:
- Temporarily remove restrictions to test, then re-add carefully.
- Confirm correct service name in API restrictions.
- Verify the consumer API documentation and quotas.
Error: YouTube API returns quota or configuration errors
- Cause: Quota limits or account settings.
- Fix:
- Check the API’s quotas in APIs & Services → Quotas.
- Use a lower request volume and simpler calls.
Cleanup
Delete the key to avoid lingering credentials:
- Delete via API Keys API (may return an operation):
ACCESS_TOKEN="$(gcloud auth print-access-token)"
DEL_RESP="$(
curl -sS -X DELETE \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
"https://apikeys.googleapis.com/v2/${KEY_RESOURCE}"
)"
echo "$DEL_RESP" | jq .
-
If the delete returns an operation name, poll it like in Step 4.
-
Verify in Console: – APIs & Services → Credentials: the key no longer exists.
Expected outcome: The API key is removed and cannot be used.
11. Best Practices
Architecture best practices
- Prefer stronger auth where supported: for Google Cloud service-to-service, use service accounts or Workload Identity rather than API keys.
- Use separate keys per environment: dev/staging/prod should not share keys.
- Use separate keys per application: avoid one “shared” key across multiple apps.
- Keep keys in the same project as the APIs they call when possible to simplify governance and quota management.
IAM/security best practices
- Least privilege:
- Limit who can create/update/delete keys.
- Further limit who can retrieve key strings.
- Separation of duties:
- Developers may request keys; platform/security approves and provisions.
- Audit and alert:
- Export audit logs to a security project.
- Alert on key creation, restriction removal, or mass deletion.
Cost best practices
- Restrict keys to specific APIs to avoid accidental usage across multiple billable APIs.
- Use budgets and alerts on the project and on major billable APIs.
- Rotate and delete unused keys to reduce the risk of abuse-driven costs.
Performance best practices
- API Keys API is not in the runtime path; performance considerations mainly apply to:
- Avoid excessive management calls in pipelines (cache inventories).
- Use exponential backoff on quota/rate errors.
Reliability best practices
- Treat key rotation as a two-phase deployment: 1. Create new key and distribute it 2. Switch traffic to new key 3. Delete old key after confirmation
- Use canary releases when changing keys for critical integrations.
Operations best practices
- Tagging and naming (where supported):
- Use consistent display names:
env-app-purpose-owner - Track owners in internal inventory systems if labels aren’t available.
- Document key ownership:
- Link to the service/application runbook.
- Record responsible team and escalation path.
Governance best practices
- Standardize:
- Which restriction types are allowed
- Minimum restrictions per key type (browser vs server vs mobile)
- Rotation interval guidelines
- Enforce via:
- CI policy checks (lint key metadata)
- Periodic audits and remediation scripts
12. Security Considerations
Identity and access model
- API Keys API management uses IAM.
- API key usage is not IAM; it’s a shared-secret token presented to consumer APIs.
- Keys should be treated as sensitive credentials even when used in client-side apps.
Encryption
- Google Cloud encrypts data at rest by default.
- The key string is sensitive; your main risk is exposure in:
- Source control
- CI logs
- Build artifacts
- Tickets/chat
- Client apps without restrictions
Network exposure
- API keys used from browsers are inherently exposed to end users.
- Mitigate by:
- HTTP referrer restrictions
- API restrictions
- Choosing server-side proxy patterns when feasible
- For server-side keys:
- Use IP restrictions if you have stable egress IPs (NAT)
- Store keys in Secret Manager and do not bake into container images
Secrets handling (critical)
- Do not hardcode key strings in repositories.
- Use Secret Manager for server-side keys and mount/inject at runtime.
- Limit who can retrieve key strings via IAM.
- Avoid printing key strings in logs and pipeline output.
- Rotate keys after suspected exposure.
Audit/logging
- Ensure Cloud Audit Logs are enabled and retained according to your policy.
- Export logs to a central project for immutable retention and SIEM ingestion if needed.
- Review:
- Key creation
- Restriction updates (especially removal)
- Key deletions
- Key-string retrieval events (verify which events are logged in your environment)
Compliance considerations
- API keys are credentials; many compliance frameworks require:
- Access control (IAM)
- Audit trails (Audit Logs)
- Rotation policies
- Incident response procedures
- If you are in a regulated environment, document:
- Who can retrieve key strings
- How keys are stored
- How rotation is performed and verified
Common security mistakes
- Unrestricted keys (no API restrictions, no app restrictions)
- Sharing one key across many apps/environments
- Checking keys into Git repos
- Storing keys in plaintext config maps or VM metadata without controls
- Allowing broad IAM roles to retrieve key strings
Secure deployment recommendations
- Apply both:
- API restrictions (limit allowed services)
- Application restrictions (referrer/IP/app)
- Store server keys only in Secret Manager.
- Use organization-level logging and alerting for key changes.
- Implement automated rotation for high-risk keys.
13. Limitations and Gotchas
Always verify current quotas and exact behaviors in official docs, since these can change.
Known limitations / nuances
- API keys are not identity: they don’t represent a user/service account and don’t carry IAM roles.
- Not all Google APIs accept API keys: many require OAuth 2.0.
- Client-side exposure: browser/mobile keys can be extracted; restrictions reduce misuse but don’t make the key “secret.”
- Restrictions must be correct: mis-typed service identifiers or wrong restriction type can break production.
- Long-running operations: create/update/delete may require polling; scripts must handle this robustly.
Quotas
- Management requests (create/update/delete/list) are quota-limited.
- There may also be limits on number of keys per project.
- Verify in Quotas and API docs.
Regional constraints
- Keys are managed under
locations/global. - Consumer APIs may have regional endpoints or data residency constraints; API key management itself is global.
Pricing surprises
- Most cost surprises come from:
- Leaked unrestricted keys used against billable APIs
- Unexpected high request volume from client apps
- Apply restrictions and budgets early.
Compatibility issues
- Some APIs accept keys in query params; others may accept headers; follow each API’s documentation.
- Some restriction types are only relevant to certain API families (for example, browser referrer restrictions are common with Maps JavaScript usage).
Operational gotchas
- Rotation requires coordination across clients; if you delete the old key too early, you cause outages.
- Inventory is necessary: without it, you won’t know which key is used where.
- CI logs can leak key strings if you print responses. Scrub logs and disable debug printing.
Migration challenges
- Migrating legacy unrestricted keys to restricted keys can break unknown consumers.
- Mitigate with:
- Discovery period (monitor usage)
- Gradual restriction (restrict by API first, then by app/IP)
- Communication and rollback plan
Vendor-specific nuances
- API restrictions depend on service names as recognized by Google Cloud (as shown in API Library / Service Usage). Always validate in your project by listing enabled services and testing.
14. Comparison with Alternatives
API Keys API is specifically about managing API keys on Google Cloud. Alternatives include other Google Cloud credential systems or API management platforms.
| Option | Best For | Strengths | Weaknesses | When to Choose |
|---|---|---|---|---|
| API Keys API (Google Cloud) | Programmatic API key lifecycle + restrictions | Automation, IAM control, audit logs, restrictions, integrates with API Library | API keys are weaker than IAM/OAuth; not all APIs accept keys | You must use API keys for a target API and need governance/automation |
| Google Cloud IAM (service accounts, OAuth) | Server-to-server auth and strong identity | Strong auth, least privilege, rotation patterns, auditable identity | Not usable where API keys are required; more setup | Prefer this for Google Cloud services where supported |
| Secret Manager (Google Cloud) | Secure storage/distribution of secrets (including API keys) | Central secret storage, versioning, access control, auditing | Doesn’t create/manage API keys; only stores them | Use alongside API Keys API for server-side key delivery |
| Apigee (Google Cloud) | Full API management for your own APIs | Policies, quota, analytics, developer portal, OAuth, key validation | More complex and cost; different purpose | You’re publishing APIs and need API gateway management |
| AWS API Gateway API Keys (AWS) | API key management for APIs behind AWS API Gateway | Tight integration with AWS gateway usage plans | Not for Google APIs; different ecosystem | You run APIs on AWS API Gateway and need keys/usage plans |
| Azure API Management subscriptions/keys (Azure) | API key/subscription management for APIs behind Azure APIM | Good for API publishing and subscriptions | Not for Google APIs; different ecosystem | You use Azure APIM as your gateway |
| Self-managed keys in database | Simple internal apps | Full control | High risk, no native audit/IAM integration, reinvents security | Only for niche cases; usually avoid if cloud-native options exist |
15. Real-World Example
Enterprise example: regulated organization controlling third-party API usage
- Problem: Multiple teams use Google APIs in production. Keys are created ad hoc, some unrestricted, and auditors require traceability.
- Proposed architecture:
- Central platform pipeline uses API Keys API to create keys with baseline restrictions (API restrictions + IP restrictions).
- Keys are stored in Secret Manager with strict IAM.
- Audit logs for API Keys API are exported to a central security project and SIEM.
- Rotation is scheduled; old keys are deleted after validation.
- Why API Keys API was chosen:
- Allows standardized, audited, automated key lifecycle management.
- Reduces manual credential sprawl and supports compliance reporting.
- Expected outcomes:
- Lower risk of leaked keys causing incidents or cost spikes.
- Faster provisioning with consistent restrictions.
- Clear audit trail of key management actions.
Startup/small-team example: controlling usage of a public Google API
- Problem: A small team ships a web app that calls a Google API using an API key. They need quick setup but want to reduce abuse risk.
- Proposed architecture:
- Use API Keys API (or Console initially) to create keys per environment.
- Apply API restrictions to only the required API.
- Apply HTTP referrer restrictions for the browser key.
- Add budgets/alerts on the project.
- Why API Keys API was chosen:
- Enables automation later (rotation, multi-env) without retooling.
- Gives a clean path to governance as the team scales.
- Expected outcomes:
- Reduced risk of “copy/paste key reuse” and unauthorized calls.
- Simple operational model with clear upgrade path.
16. FAQ
-
What is API Keys API in Google Cloud?
It’s the management API (apikeys.googleapis.com) for creating, updating, restricting, and deleting API keys in a Google Cloud project. -
Is API Keys API the same as “Credentials” in the Console?
The Console under APIs & Services → Credentials is the UI experience; API Keys API is the programmatic interface. They manage the same general type of API key resources. -
Are API keys a secure authentication method?
They are a shared secret and generally weaker than OAuth/service accounts. Use restrictions and prefer stronger identity methods where supported. -
Can I use API keys for Google Cloud service-to-service calls?
Many Google Cloud APIs use OAuth/service accounts. Some endpoints accept API keys, but best practice is IAM-based auth. Verify per API. -
What’s the biggest risk with API keys?
Exposure (in source code, logs, client apps) leading to unauthorized usage and potential cost spikes—especially if keys are unrestricted. -
What are API restrictions vs application restrictions?
API restrictions limit which APIs the key can call. Application restrictions limit where the key can be used from (referrer/IP/app identity). -
Do I still need to enable APIs in the project?
Yes. The API must be enabled via API Library/Service Usage for it to be callable with the key. -
How do I find the correct service name for API restrictions?
Use APIs & Services → Enabled APIs & services orgcloud services list --enabled. Use the service identifier shown there. -
Can I retrieve the API key string after creation?
Yes, API Keys API provides a way to retrieve the key string. Treat it as sensitive and restrict IAM permissions for that action. -
Should I store API keys in Secret Manager?
For server-side usage, yes. For browser/mobile keys, you cannot fully hide them; use restrictions and consider a backend proxy if appropriate. -
How do I rotate an API key safely?
Create a new key, distribute it, update clients, validate, then delete the old key. Avoid deleting the old key before confirming rollout. -
Can I have different keys for dev/staging/prod?
Yes, and it’s recommended. Prefer separate projects and separate keys to isolate risk. -
What logs exist for API Keys API operations?
Administrative actions are captured in Cloud Audit Logs. Verify which event types are recorded for key-string retrieval in your environment. -
Does restricting a key break existing applications?
It can. Apply restrictions carefully and test. Consider a staged rollout (API restrictions first, then app/IP restrictions). -
What should I do if a key is leaked?
Delete or rotate the key immediately, review usage and billing, and add stricter restrictions. Also remove it from the source of exposure and invalidate caches/configs. -
Are API keys tied to a user?
No. Keys are resources in a project. Anyone with the key string can use it (subject to restrictions). -
Can I manage API keys via Terraform?
Tooling support changes over time. If you use IaC, verify current provider support and consider the secret-handling implications. Many teams prefer API-driven workflows plus Secret Manager for sensitive values.
17. Top Online Resources to Learn API Keys API
| Resource Type | Name | Why It Is Useful |
|---|---|---|
| Official documentation | API Keys API docs — https://cloud.google.com/api-keys/docs | Primary source for concepts, restrictions, and workflows |
| API reference | API Keys API REST reference — https://cloud.google.com/api-keys/docs/reference/rest | Exact endpoints, request/response schemas, update masks |
| Console guide | APIs & Services → Credentials (Console) — https://cloud.google.com/docs/authentication/api-keys | Practical UI-based key creation and restriction guidance |
| Pricing overview | Google Cloud pricing — https://cloud.google.com/pricing | Understand general pricing and billing concepts |
| Pricing calculator | Google Cloud Pricing Calculator — https://cloud.google.com/products/calculator | Estimate costs for consumer APIs and related services |
| IAM overview | IAM documentation — https://cloud.google.com/iam/docs | Learn roles, permissions, least privilege |
| Audit logs | Cloud Audit Logs — https://cloud.google.com/logging/docs/audit | How to find and export admin activity for key management |
| Secret storage | Secret Manager — https://cloud.google.com/secret-manager/docs | Best practice for storing server-side API keys |
| Service enablement | Service Usage — https://cloud.google.com/service-usage/docs | Enable/disable APIs and discover service names |
| CLI tool | gcloud services — https://cloud.google.com/sdk/gcloud/reference/services | Enable/list services and discover enabled API identifiers |
| Architecture guidance | Google Cloud Architecture Center — https://cloud.google.com/architecture | Broader patterns for secure application development |
18. Training and Certification Providers
| Institute | Suitable Audience | Likely Learning Focus | Mode | Website URL |
|---|---|---|---|---|
| DevOpsSchool.com | DevOps engineers, SREs, platform teams | CI/CD, cloud automation, operational best practices around cloud services | Check website | https://www.devopsschool.com/ |
| ScmGalaxy.com | Beginners to intermediate engineers | Software configuration management, DevOps foundations, tooling practices | Check website | https://www.scmgalaxy.com/ |
| CLoudOpsNow.in | Cloud operations and engineering teams | Cloud operations patterns, governance, reliability | Check website | https://www.cloudopsnow.in/ |
| SreSchool.com | SREs, reliability engineers | SRE practices, monitoring, incident response applied to cloud systems | Check website | https://www.sreschool.com/ |
| AiOpsSchool.com | Ops teams adopting automation | AIOps concepts, automation, operational analytics | Check website | https://www.aiopsschool.com/ |
19. Top Trainers
| Platform/Site | Likely Specialization | Suitable Audience | Website URL |
|---|---|---|---|
| RajeshKumar.xyz | DevOps/cloud training content (verify offerings) | Students, engineers seeking hands-on guidance | https://rajeshkumar.xyz/ |
| devopstrainer.in | DevOps training (verify course catalog) | DevOps engineers, developers moving into operations | https://www.devopstrainer.in/ |
| devopsfreelancer.com | Freelance DevOps services/training (verify offerings) | Teams needing practical help and mentoring | https://www.devopsfreelancer.com/ |
| devopssupport.in | DevOps support/training resources (verify offerings) | Ops teams needing implementation support | https://www.devopssupport.in/ |
20. Top Consulting Companies
| Company | Likely Service Area | Where They May Help | Consulting Use Case Examples | Website URL |
|---|---|---|---|---|
| cotocus.com | Cloud/DevOps consulting (verify service scope) | Delivery automation, cloud architecture, operational readiness | Designing key rotation workflows; securing CI/CD; governance patterns for credentials | https://cotocus.com/ |
| DevOpsSchool.com | DevOps consulting and training (verify service catalog) | Platform enablement, DevOps transformation, best practices | Building standardized API key management + Secret Manager patterns; implementing audit log exports | https://www.devopsschool.com/ |
| DEVOPSCONSULTING.IN | DevOps consulting (verify capabilities) | CI/CD, cloud operations, automation | Creating secure pipelines that provision and rotate API keys; setting up monitoring and budgets | https://www.devopsconsulting.in/ |
21. Career and Learning Roadmap
What to learn before API Keys API
- Google Cloud fundamentals:
- Projects, billing accounts, IAM basics
- APIs & Services (API Library, enabling services)
- Authentication fundamentals:
- API keys vs OAuth 2.0 vs service accounts
- Basic security practices:
- Secrets handling, least privilege
- Tooling:
gcloudbasics, Cloud Shell, REST calls withcurl
What to learn after API Keys API
- Stronger identity patterns on Google Cloud:
- Service accounts and IAM best practices
- Workload Identity (GKE) and Workload Identity Federation (external workloads)
- Secret management patterns:
- Secret Manager replication, rotation, access policies
- Governance and operations:
- Cloud Audit Logs sinks, log-based alerting
- Budgets and billing alerts
- API management (if you publish your own APIs):
- Apigee or API Gateway patterns
Job roles that use it
- Cloud Engineer / DevOps Engineer
- Site Reliability Engineer (SRE)
- Platform Engineer
- Security Engineer (cloud governance, credential controls)
- Application Developer integrating Google APIs
Certification path (if available)
There is no certification specifically for API Keys API, but it fits within: – Associate Cloud Engineer (Google Cloud) – Professional Cloud Developer – Professional Cloud Security Engineer – Professional Cloud DevOps Engineer
(Verify current certification tracks here: https://cloud.google.com/learn/certification)
Project ideas for practice
- Key inventory reporter: list keys, check which are unrestricted, produce a report.
- Automated rotation pipeline: create new key, store in Secret Manager, update a service config, delete old key.
- Guardrail checker: CI job that blocks merges if a repository contains patterns resembling API keys.
- Incident response automation: script that deletes a key by name and writes an audit entry to a ticketing system.
- Multi-environment key manager: standardized naming and restrictions for dev/staging/prod projects.
22. Glossary
- API Key: A string token used to identify and authorize requests to some Google APIs. Not a user identity.
- API Keys API: Google Cloud management API to programmatically manage API keys (
apikeys.googleapis.com). - API Restrictions: A restriction that limits which Google APIs/services a key can call.
- Application Restrictions: Restrictions that limit where the key can be used from (HTTP referrer, IP, Android app, iOS app).
- IAM (Identity and Access Management): Google Cloud system for authorization—who can do what on which resources.
- Service Usage: Google Cloud service that controls enabling/disabling APIs in a project and tracks consumption.
- Cloud Audit Logs: Logs that record administrative actions and access patterns for Google Cloud resources.
- Secret Manager: Google Cloud service for storing, versioning, and accessing secrets securely.
- Long-running Operation: An API pattern where a request returns an operation resource that you poll until completion.
- Project Number: Numeric identifier of a Google Cloud project, often used in resource names.
- Least Privilege: Security principle of granting only the minimum permissions necessary.
- Rotation: Replacing an old credential with a new one on a schedule or after exposure.
23. Summary
API Keys API (Google Cloud) is the control-plane service for managing API keys programmatically—creating them, restricting them, retrieving key strings when needed, rotating them, and deleting them with IAM-backed authorization and audit trails. It matters because API keys are easy to misuse at scale: without governance, they sprawl, get exposed, and can drive unexpected cost and security incidents.
In the Google Cloud Application development toolbox, API Keys API fits when you must use API keys for supported Google APIs and you want automation, consistency, and security guardrails. Cost-wise, the largest driver is almost always the consumer APIs called with the key, not key management itself—so restrictions, budgets, and monitoring are essential. Security-wise, apply both API restrictions and application restrictions, store server-side keys in Secret Manager, and tightly control who can retrieve key strings.
Next step: implement a small internal “key management” workflow (inventory + baseline restrictions + rotation) and connect it to your CI/CD so key governance becomes routine rather than an emergency response.