[Free Article 2] Done in 3 minutes! Google Gemini API Key Acquisition and GAS Environment Setup
Hello! In Free Article 1, we completed the foundation for the X automated posting system (semi-automation). In this article, we will configure the settings to let AI handle the writing of the post content.
We will use the API for Gemini, a high-performance AI model provided by Google. Once you obtain the key and set it in GAS, you can immediately integrate with AI.
Part 1: Obtaining the Gemini API Key
First, we will obtain the authentication key to use the Google Gemini API.
1-1. Access Google AI Studio
Access the Google AI Studio page below and log in with your Google account.

1-2. Creating an API Key
After logging in, click the "Get API key" button at the bottom of the menu on the left side of the screen.
A new key will be issued immediately.

Once the API key is issued, click the link in the red box in the image above to display the API key. You can copy the key using the copy button to the right of the API key.

This key is required for setting it in GAS in Part 4. Be sure to copy it to a safe place and keep a note of it.
🚨 Most Important Warning!: This key is like a very important password that gives the API permission to access your Google account. Please manage it strictly so that it is not known to others.
Part 2: Pasting the code into GAS
Open the GAS project created in Part 1 and add the JavaScript code to communicate with the Gemini API.
2-1. Create a new script file
From the menu on the left side of the GAS editor, select "+" (Add file) -> "Script", and save the file name as "GeminiIntegration".
2-2. Paste the integration code
In the newly created GeminiIntegration.js, delete the existing code, paste the entire code below, and save it.
// --- Gemini API 連携コード ---
/**
* スクリプトプロパティから API キーを安全に取得します。
* @return {string} Gemini API キー
* @throws {Error} キーが設定されていない場合
*/
function getApiKey() {
const props = PropertiesService.getScriptProperties();
const apiKey = props.getProperty('GEMINI_API_KEY');
if (!apiKey) {
// ユーザーに設定漏れを通知するためのエラー
throw new Error('スクリプトプロパティに "GEMINI_API_KEY" が設定されていません。Part 4-1 を確認してください。');
}
return apiKey;
}
/**
* Gemini API を呼び出し、プロンプトに基づいてテキストを生成します。
* @param {string} prompt AI に与える指示(プロンプト)
* @return {string} Gemini が生成したテキスト
* @throws {Error} API 呼び出しに失敗した場合
*/
function callGeminiApi(prompt) {
const apiKey = getApiKey();
// 使用するモデル (gemini-2.5-flash) と API エンドポイント
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key=${apiKey}`;
// API に送信するペイロード (リクエスト本体)
const payload = {
contents: [{ parts: [{ text: prompt }] }],
// リアルタイム情報を参照したい場合は以下のツール設定のコメントを解除してください
// tools: [{ "google_search": {} }],
};
const options = {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(payload),
// HTTP エラーを例外として処理できるようにします
muteHttpExceptions: true
};
try {
const response = UrlFetchApp.fetch(apiUrl, options);
const responseCode = response.getResponseCode();
const responseText = response.getContentText();
if (responseCode !== 200) {
Logger.log(`APIエラー (コード: ${responseCode}): ${responseText}`);
throw new Error(`Gemini API 呼び出しに失敗しました。応答: ${responseText.substring(0, 100)}...`);
}
const result = JSON.parse(responseText);
// 応答から生成されたテキスト部分を抽出
const generatedText = result.candidates?.[0]?.content?.parts?.[0]?.text || "応答が空でした。";
return generatedText;
} catch (e) {
Logger.log('Gemini API 呼び出しエラー: ' + e.message);
// 処理を停止せず、エラーメッセージを返すことも可能です
return `AI生成エラー: ${e.message}`;
}
}
/**
* Gemini API の動作をテストするための関数です。
* 成功すると、ログに AI の自己紹介が表示されます。
*/
function testGeminiApi() {
const testPrompt = "AIライティングアシスタントとして、自己紹介をしてください。返答は1文でお願いします。";
try {
const response = callGeminiApi(testPrompt);
// ログに出力
Logger.log("========================================");
Logger.log("✅ Gemini API テスト成功");
Logger.log("プロンプト: " + testPrompt);
Logger.log("応答: " + response);
Logger.log("========================================");
// ユーザーへの通知
Browser.msgBox("Gemini APIテスト完了", "ログを確認してください。成功していればAIの自己紹介が表示されています。", Browser.Buttons.OK);
} catch(e) {
// 失敗した場合の処理
Logger.log("========================================");
Logger.log("❌ Gemini API テスト失敗");
Logger.log("エラー: " + e.message);
Logger.log("========================================");
Browser.msgBox("Gemini APIテスト失敗", "ログを確認してください。エラーメッセージが表示されています。", Browser.Buttons.OK);
}
}This code includes three functions: "Obtaining the API key," "Executing the Gemini API call," and "Simple operation test."
Part 3: Registering the key to script properties
We will safely save the Gemini API key in the GAS settings area.
3-1. Open script properties
Click the "Project Settings" (⚙️) icon from the menu on the left side of the GAS editor.
3-2. Register GEMINI_API_KEY

Find the "Script Properties" section, click "Edit script properties," and add the following one key and value exactly, then save it.
Property: GEMINI_API_KEY
Value:The entire API key obtained in Part 1-2
Description:Key for integration with the Gemini API
Part 4: Running the operation test
Test the AI call to verify that the key was set correctly.
4-1. Run the testGeminiApi function
Select "testGeminiApi" from the function dropdown menu at the top of the GAS editor screen and click "Run".
You will be asked for permission by Google only during the first execution (permission to connect to external services). Please grant all permissions to proceed.
*If you have already granted permission in Free Article 1, this should not appear.
4-2. Check the logs
Once execution is complete, check the "Execution log" at the bottom of the screen.

If successful, "✅ Gemini API test successful" and the AI's self-introduction will be displayed.
If it fails, "❌ Gemini API test failed" and an error message will be displayed. In this case, please double-check that the GEMINI_API_KEY value is correct.
After checking, stop the execution.
🔑 Summary: Moving to the next step
The environment for the AI to generate text is now ready!
By combining the X integration from Part 1 with the Gemini integration from this Part 2, the fully automated scheduled posting system will be complete.
Coming soon ⬇️
[→ Automation! To the final code and settings for AI text generation and scheduled posting to X]
