このクイックスタートでは、ライブラリをインストールして最初の 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
- 新しい Apps Script プロジェクトを作成するには、script.new に移動します。
- [無題のプロジェクト] をクリックします。
- Apps Script プロジェクトの名前を AI Studio に変更して、[名前を変更] をクリックします。
- API キーを設定する
- 左側の [プロジェクト設定]
をクリックします。
- [スクリプト プロパティ] で [スクリプト プロパティを追加] をクリックします。
- [プロパティ] にキー名
GEMINI_API_KEY
を入力します。 - [値] に API キーの値を入力します。
- [スクリプト プロパティを保存] をクリックします。
- 左側の [プロジェクト設定]
Code.gs
ファイルの内容を次のコードに置き換えます。
最初のリクエストを送信する
generateContent
メソッドを使用して Gemini 2.5 Flash モデルを使用して Gemini API にリクエストを送信する例を次に示します。
Python
from google import genai
client = genai.Client(api_key="YOUR_API_KEY")
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";
const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });
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()
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.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 `GOOGLE_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?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);
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-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"
}
]
}
]
}'
多くのコードサンプルでは、デフォルトで「思考」がオンになっています
このサイトの多くのコードサンプルでは、Gemini 2.5 Flash モデルを使用しています。このモデルでは、回答の質を高めるために、「思考」機能がデフォルトで有効になっています。これにより、レスポンス時間とトークンの使用量が増加する可能性があります。速度を優先する場合や費用を最小限に抑えたい場合は、次の例に示すように、思考予算をゼロに設定してこの機能を無効にできます。詳しくは、思考ガイドをご覧ください。
Python
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
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({ apiKey: "GEMINI_API_KEY" });
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, _ := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
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?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?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);
}
次のステップ
最初の API リクエストを実行したので、Gemini の動作を示す次のガイドを確認することをおすすめします。