The shortest path to the Gemini API is this: open AI Studio with a Google account, create an API key, install the SDK, and send your first generateContent request. When everything goes smoothly, the whole process takes less than twenty minutes. The real stumbling blocks are not "can I connect at all" but choosing the wrong entry point, typing the model ID incorrectly, confusing the free tier with paid usage, and putting the key somewhere it does not belong.

This article follows the actual setup order: distinguish AI Studio from Vertex AI, create a key, install the SDK, send curl and Python requests, then handle model naming, system instructions, streaming output, and safety settings. It closes with common causes of 400, 403, and 429 errors and a key-safety checklist.

Note: Google and Gemini are trademarks of Google LLC. Model names, free-tier quotas, and billing rules may change. This article describes the common flow as of October 2026; follow Google's documentation and the model pricing page for current details.

1. First, distinguish AI Studio from Vertex AI

The Gemini API has two common entry points with different account systems and management models. Choosing the wrong one leads to rework around permissions or billing.

Comparison Google AI Studio Vertex AI
Entry Browser console for quick developer trials Google Cloud console for project-based use
Account requirements A Google account is enough to start Cloud project, billing account, and IAM permissions
Credentials API key generated in AI Studio Service account or controlled key with IAM
Billing Free and paid tiers coexist Billed through the Cloud project
Regions and data Governed by AI Studio terms Selectable regions, subject to Cloud terms and project configuration
Best for Prototypes, learning, small-scale validation Production systems and teams with audit and permission requirements

Individual developers and small teams usually get the flow working in AI Studio first, then evaluate Vertex AI when contracts, data regions, or unified auditing come into play. Do not mix keys, quotas, and bills between the two, and do not use an AI Studio key to call Vertex AI endpoints.

2. Create your first API key

  1. Sign in to Google AI Studio with a Google account.
  2. Open the API key management page and choose to create an API key.
  3. Select a Google Cloud project; if you do not have one, create one as prompted.
  4. Copy the generated key and immediately store it in a server-side environment variable or password manager.
  5. Send a test message in the Playground to confirm the key and model work.
  6. Give the key a name that shows its purpose, to make future rotation and revocation easier.

AI Studio offers a free tier for trials, but available models, request rates, and quotas vary by account and time period. After billing is enabled on the associated Cloud project, you can move to the paid tier. Do not treat quota numbers from older articles as a current commitment; the console display and vendor documentation are authoritative.

After creating a key, confirm which Cloud project it belongs to. Quotas are usually calculated per project, so mixing testing and production can let one team exhaust another's quota. If you need a higher quota, enable billing on the Cloud project, set a budget alert, and observe actual usage for a week first.

3. Install the SDK and send your first request

Use Python 3.10 or later and install the vendor SDK in a virtual environment.

python3 -m venv .venv
source .venv/bin/activate
pip install -U google-genai
export GEMINI_API_KEY="your-key"

Use curl first to rule out SDK issues. Replace the model ID placeholder below; get the actual name from the model list or the pricing page.

curl "https://generativelanguage.googleapis.com/v1beta/models/<MODEL_ID>:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "Explain in one sentence what an API gateway is"}]}
    ],
    "generationConfig": {"maxOutputTokens": 256, "temperature": 0.7}
  }'

Once curl returns 200, switch to the Python SDK:

import os
from google import genai

client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])

resp = client.models.generate_content(
    model="<MODEL_ID>",
    contents="Explain in one sentence what an API gateway is",
)
print(resp.text)

model must be the complete model ID, not just the series name. Different models support different input types and parameters, and mistakes show up as 400 or 404 errors.

4. Model naming, system instructions, and generation parameters

Gemini model IDs usually combine a series and a version. The safest approach is to query the model list available to the current account first:

curl "https://generativelanguage.googleapis.com/v1beta/models" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

Do not guess model names that are not on the list. When choosing, assign by task: use the low-latency tier for lightweight work and the higher tier for complex reasoning and long documents. Specific tiers and prices follow the model pricing page.

Model IDs change with versions, and old IDs may be marked deprecated or retired. Put model names in a configuration file instead of scattering them across the codebase, so upgrades change one place and regression samples can confirm that output has not shifted noticeably.

System instructions fix the role and output rules, which suits translation, extraction, and customer support scenarios:

resp = client.models.generate_content(
    model="<MODEL_ID>",
    contents="Translate this sentence into English: integration complete",
    config={"system_instruction": "You are a technical documentation translator. Output only the translation."},
)

Common generation parameters include temperature, maxOutputTokens, and topP. When you need structured results, you can ask the model to return JSON and then parse and validate it in code. Do not assume the model will always follow the format; write retry and fallback logic in advance.

5. Streaming output and safety settings

Streaming suits chat interfaces and long answers. For REST, add :streamGenerateContent after the method and include alt=sse; with the Python SDK, use generate_content_stream:

for chunk in client.models.generate_content_stream(
    model="<MODEL_ID>",
    contents="Explain rate limiting in three points",
):
    print(chunk.text, end="")

Safety settings can adjust blocking thresholds by category; common categories include harassment, hate speech, sexually explicit content, and dangerous content. Default thresholds suit most businesses. Lowering the threshold broadens what content is allowed and should be evaluated against product policy and local regulations. Do not turn safety settings off across the board just to "pass testing," especially for public-facing products.

6. Troubleshooting 400, 403, and 429

Status Common cause Direction
400 Malformed JSON, unsupported parameter, model ID incompatible with the endpoint Check the request body field by field; start with a minimal request
403 Invalid or restricted key, API not enabled, project or region restriction Try another key; check project permissions and account status
404 Misspelled model ID, wrong API version or path Check the model list and confirm v1beta and the method name
429 Free-tier quota exhausted, too many requests per minute, high concurrency Retry with exponential backoff, reduce concurrency, evaluate the paid tier
500/503 Temporary server-side failure Retry a limited number of times; degrade or switch channels if it persists

Do not resend immediately on a 429. The right approach is backoff with random jitter, a maximum retry count, and logging of failed requests. Free-tier rate limits are usually tighter, so load tests and batch jobs should be scheduled separately.

7. Key safety checklist

  • Store keys only in server-side environment variables or a secrets manager; never in the frontend, the repository, or chat history.
  • Use separate keys for production, testing, and development, with quotas and permissions isolated by environment.
  • Rotate regularly, and revoke immediately when staff leave or a project ends.
  • In the cloud console, restrict which APIs a key can call to reduce the impact of a leak.
  • Enable usage alerts; when abnormal calls appear, disable the key first and investigate second.
  • Never expose a complete key in screenshots, screen recordings, or support tickets.

8. Using Gemini through an OpenAI-compatible endpoint

If your team already has the OpenAI SDK and a full set of calling code, you can use the OpenAI-compatible endpoint of ZSQH AI Gateway. The base URL is https://ai.zhongshangqihang.com/v1; only three things change: base_url, api_key, and model.

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["ZSQH_API_KEY"],
    base_url="https://ai.zhongshangqihang.com/v1",
)

resp = client.chat.completions.create(
    model="<Gemini model name from the pricing page>",
    messages=[{"role": "user", "content": "Reply with OK only"}],
)
print(resp.choices[0].message.content)

This approach suits teams that need unified multi-model billing, billing in Chinese yuan, and a network path that works well from mainland China. Native Gemini parameters and multimodal fields are not automatically equivalent; verify each item with real requests before migrating. The registration page is here, and models and prices follow the model pricing page.

FAQ

Does the Gemini API have a free tier?

AI Studio offers a free tier, but available models, rates, and quotas change, and data terms may differ from the paid tier. The free tier is fine for prototypes; for production, re-evaluate quotas and costs under the paid tier.

What should I do if an API key leaks?

First revoke or rotate the key in the console, then check usage logs to determine the scope of abnormal calls, and finally investigate the leak channel. Deleting the key from code is not enough; treat any exposed credential as compromised.

Can the Gemini API be called directly from mainland China?

Link quality varies by region and carrier, and timeouts or connection failures can occur. Common approaches are to place requests on a server with stable access or to use a gateway that supports OpenAI-compatible interfaces. Specific limits depend on the actual network path and vendor documentation.

Why does curl work while the Python SDK fails?

Check whether the SDK version and dependencies are current, then confirm that model, proxy settings, and environment variables are consistent. If the SDK returns 404, focus on the model ID and endpoint path, and do not change several variables at once.

Can the Gemini API be called directly with the OpenAI SDK?

Google provides an OpenAI-compatible endpoint, and many gateways also provide a compatibility layer, but parameter support differs. Multimodal input, tool calling, and structured output should be verified with real requests; do not assume they are fully equivalent.

Next steps

Get the minimal request working using the flow above, then add business logging, retries, and usage monitoring. If you want to manage Gemini and other models' usage, yuan billing, and key permissions from one console, you can sign up for ZSQH AI Gateway; prices are on the model pricing page.

Related reading: