0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Node.jsでAIのAPIを叩いてみよう

0
Last updated at Posted at 2026-02-12

AIのAPIをCurlで叩いてみる
https://qiita.com/toshirot/items/ffd243750d5b3d407d18

という記事を書いたので、その続きとして Node.jsでAIのAPIを叩いてみようと思います。とりまChatGPT(OpenAI)APIから。Geminiも同様です。

Node.jsでの準備

前回のCurlは-d を指定しているのでGETではなくPOSTを投げている。そこでPOSTを使ってコード化してみる。
まずはnode-fetchを使う方法。npmでnode-fetchをインストールしておく。
※Node.js v18以降なら、fetchが標準で使える
参考:Node.jsのバージョン確認方法:

$ node -v
v20.19.6

もし、このバージョンがv18未満なら下記npmなどでインストールしておく

npm install node-fetch

nde.jsコード

下記サンプルはAPI_KEYをコード内に埋め込んでいるので、ブラウザなど外部からは覗かれない場所においてください。実際の運用では、APIキーは環境変数などで安全に管理しましょう!

ファイル名 fetch2openai.js

/*
APIキーとエンドポイントの準備
これは前回API取得で使った「[ChatGPT(OpenAI)APIキー発行・確認・再発行ページ](https://platform.openai.com/api-keys)」でOpenAIのAPIキーを取得する。
*/

const fetch = require('node-fetch'); // v18未満の場合のみ必要

const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxx';
const endpoint = 'https://api.openai.com/v1/chat/completions';

// fetchでPOSTリクエストを送る

async function callChatGPT() {
  const response = await fetch(endpoint, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${API_KEY}`
    },
    body: JSON.stringify({
      model: 'gpt-3.5-turbo',
      messages: [
        { role: 'user', content: 'あなたはAIアシスタントです。自己紹介を1文でしてください。' }
      ]
    })
  });

  const data = await response.json();
  console.log(data.choices[0].message.content);

}

callChatGPT();

このdata.choices[0].message.contentがAIからのレスポンス文字列ですので、これを使っていろいろな操作が可能になります。

結果

$ node fetch2openai.js
私はAIアシスタントで、質問やサポートが必要な際にお手伝いします。
$ node fetch2openai.js
はじめまして、AIアシスタントです。どうぞお気軽に質問やお困りごとをお知らせください。
$ node fetch2openai.js
私はAIアシスタントで、あなたの質問やお手伝いをすることができます。

OpenAI(ChatGPT)API の公式リファレンスはこちら
https://platform.openai.com/docs/api-reference
(platform.openai.com in Bing)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?