Gemini API のクイックスタート

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

始める前に

Gemini API キーが必要です。キーがない場合は、Google AI Studio で無料で取得できます。

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

Python

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

pip install -q -U google-genai 

JavaScript

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

npm install @google/genai 

Go

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

go get google.golang.org/genai 

Java

Maven を使用している場合は、依存関係に次のものを追加して google-genai をインストールできます。

<dependencies>   <dependency>     <groupId>com.google.genai</groupId>     <artifactId>google-genai</artifactId>     <version>1.0.0</version>   </dependency> </dependencies> 

Apps Script

  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 2.5 Flash モデルを使用して Gemini API にリクエストを送信します。

API キーを環境変数 GEMINI_API_KEY として設定すると、Gemini API ライブラリを使用するときに、クライアントによって自動的に取得されます。それ以外の場合は、クライアントを初期化するときに引数として API キーを渡す必要があります。

Gemini API ドキュメントのすべてのコードサンプルでは、環境変数 GEMINI_API_KEY が設定されていることを前提としています。

Python

from google import genai  # The client gets the API key from the environment variable `GEMINI_API_KEY`. client = genai.Client()  response = client.models.generate_content(     model="gemini-2.5-flash", contents="Explain how AI works in a few words" ) print(response.text) 

JavaScript

import { GoogleGenAI } from "@google/genai";  // The client gets the API key from the environment variable `GEMINI_API_KEY`. const ai = new GoogleGenAI({});  async function main() {   const response = await ai.models.generateContent({     model: "gemini-2.5-flash",     contents: "Explain how AI works in a few words",   });   console.log(response.text); }  main(); 

Go

package main  import (     "context"     "fmt"     "log"     "google.golang.org/genai" )  func main() {     ctx := context.Background()     // The client gets the API key from the environment variable `GEMINI_API_KEY`.     client, err := genai.NewClient(ctx, nil)     if err != nil {         log.Fatal(err)     }      result, err := client.Models.GenerateContent(         ctx,         "gemini-2.5-flash",         genai.Text("Explain how AI works in a few words"),         nil,     )     if err != nil {         log.Fatal(err)     }     fmt.Println(result.Text()) } 

Java

package com.example;  import com.google.genai.Client; import com.google.genai.types.GenerateContentResponse;  public class GenerateTextFromTextInput {   public static void main(String[] args) {     // The client gets the API key from the environment variable `GEMINI_API_KEY`.     Client client = new Client();      GenerateContentResponse response =         client.models.generateContent(             "gemini-2.5-flash",             "Explain how AI works in a few words",             null);      System.out.println(response.text());   } } 

Apps Script

// 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.5-flash:generateContent';   const options = {     method: 'POST',     contentType: 'application/json',     headers: {       'x-goog-api-key': apiKey,     },     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); } 

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \   -H "x-goog-api-key: $GEMINI_API_KEY" \   -H 'Content-Type: application/json' \   -X POST \   -d '{     "contents": [       {         "parts": [           {             "text": "Explain how AI works in a few words"           }         ]       }     ]   }' 

多くのコードサンプルで「思考」がデフォルトでオンになっています

このサイトの多くのコードサンプルでは、Gemini 2.5 Flash モデルを使用しています。このモデルでは、回答の質を高めるために「思考」機能がデフォルトで有効になっています。これにより、応答時間とトークン使用量が増加する可能性があります。スピードを優先する場合や、費用を最小限に抑えたい場合は、次の例に示すように、思考予算をゼロに設定してこの機能を無効にできます。詳しくは、思考ガイドをご覧ください。

Python

from google import genai from google.genai import types  client = genai.Client()  response = client.models.generate_content(     model="gemini-2.5-flash",     contents="Explain how AI works in a few words",     config=types.GenerateContentConfig(         thinking_config=types.ThinkingConfig(thinking_budget=0) # Disables thinking     ), ) print(response.text) 

JavaScript

import { GoogleGenAI } from "@google/genai";  const ai = new GoogleGenAI({});  async function main() {   const response = await ai.models.generateContent({     model: "gemini-2.5-flash",     contents: "Explain how AI works in a few words",     config: {       thinkingConfig: {         thinkingBudget: 0, // Disables thinking       },     }   });   console.log(response.text); }  await main(); 

Go

package main  import (   "context"   "fmt"   "os"   "google.golang.org/genai" )  func main() {    ctx := context.Background()   client, err := genai.NewClient(ctx, nil)   if err != nil {       log.Fatal(err)   }    result, _ := client.Models.GenerateContent(       ctx,       "gemini-2.5-flash",       genai.Text("Explain how AI works in a few words"),       &genai.GenerateContentConfig{         ThinkingConfig: &genai.ThinkingConfig{             ThinkingBudget: int32(0), // Disables thinking         },       }   )    fmt.Println(result.Text()) } 

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \   -H "x-goog-api-key: $GEMINI_API_KEY" \   -H 'Content-Type: application/json' \   -X POST \   -d '{     "contents": [       {         "parts": [           {             "text": "Explain how AI works in a few words"           }         ]       }     ]     "generationConfig": {       "thinkingConfig": {         "thinkingBudget": 0       }     }   }' 

Apps Script

// 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.5-flash:generateContent';   const options = {     method: 'POST',     contentType: 'application/json',     headers: {       'x-goog-api-key': apiKey,     },     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); } 

次のステップ

最初の API リクエストを作成したので、Gemini の動作を示す次のガイドをご覧ください。