Gemini API のクイックスタート

このクイックスタートでは、ライブラリをインストールして最初の Gemini API リクエストを行う方法について説明します。

始める前に

Gemini API キーが必要です。まだアカウントを取得していない場合は、Google AI Studio で無料で取得できます。

Google GenAI SDK をインストールする

Python 3.9 以降を使用して、次の pip コマンドを使用して google-genai パッケージをインストールします。

pip install -q -U google-genai

Node.js v18+ を使用して、次の npm コマンドを使用して Google Gen AI SDK for TypeScript and JavaScript をインストールします。

npm install @google/genai

go get コマンドを使用して、モジュール ディレクトリに google.golang.org/genai をインストールします。

go get google.golang.org/genai
  1. 新しい Apps Script プロジェクトを作成するには、script.new に移動します。
  2. [無題のプロジェクト] をクリックします。
  3. Apps Script プロジェクトの名前を AI Studio に変更して、[名前を変更] をクリックします。
  4. API キーを設定する
    1. 左側の [プロジェクト設定] プロジェクト設定のアイコン をクリックします。
    2. [スクリプト プロパティ] で [スクリプト プロパティを追加] をクリックします。
    3. [プロパティ] にキー名 GEMINI_API_KEY を入力します。
    4. [] に API キーの値を入力します。
    5. [スクリプト プロパティを保存] をクリックします。
  5. Code.gs ファイルの内容を次のコードに置き換えます。

最初のリクエストを送信する

generateContent メソッドを使用して、Gemini API にリクエストを送信します。

from google import genai

client = genai.Client(api_key="YOUR_API_KEY")

response = client.models.generate_content(
    model="gemini-2.0-flash", contents="Explain how AI works in a few words"
)
print(response.text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: "Explain how AI works in a few words",
  });
  console.log(response.text);
}

main();
package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, &genai.ClientConfig{
        APIKey:  "YOUR_API_KEY",
        Backend: genai.BackendGeminiAPI,
    })
    if err != nil {
        log.Fatal(err)
    }

    result, err := client.Models.GenerateContent(
        ctx,
        "gemini-2.0-flash",
        genai.Text("Explain how AI works in a few words"),
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(result.Text())
}
// See https://developers.google.com/apps-script/guides/properties
// for instructions on how to set the API key.
const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
function main() {
  const payload = {
    contents: [
      {
        parts: [
          { text: 'Explain how AI works in a few words' },
        ],
      },
    ],
  };

  const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;
  const options = {
    method: 'POST',
    contentType: 'application/json',
    payload: JSON.stringify(payload)
  };

  const response = UrlFetchApp.fetch(url, options);
  const data = JSON.parse(response);
  const content = data['candidates'][0]['content']['parts'][0]['text'];
  console.log(content);
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$YOUR_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works in a few words"
          }
        ]
      }
    ]
  }'

次のステップ

最初の API リクエストを実行したので、Gemini の動作を示す次のガイドを確認することをおすすめします。