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?

envファイルからAPIキーを呼び出してOpenAIのAPIを使う

Posted at

React Nativeでアプリ開発を進める中で、APIキーや環境ごとの設定値を管理する必要が出てきます。このような場合、react-native-configを使用すれば簡単に.envファイルを利用して環境変数を管理できます。

手順

導入はいつも通りのnpm installで。

npm install react-native-config // ライブラリのインストール
cd ios && pod install && cd .. // iosのリンク

プロジェクトのディレクトリ直下に.envファイルを作成し、APIキーを記述します。

(.env)
OPENAI_API_KEY=<APIキー>

!!.gitignoreにて.envファイルを管理対象外に設定するのを忘れずに!!

(.gitignore)
.env

.tsxファイルでreact-native-configのインポートをすれば、完了。

以下はChatGPTのAPIでの呼び出し例。

import Config from 'react-native-config';

const completion = await fetch('https://api.openai.com/v1/chat/completions', {
	method: 'POST',
	headers: {
		'Content-Type': 'application/json',
		'Authorization': `Bearer ${Config.OPENAI_API_KEY}`, // APIキー呼び出し
	},
	body: JSON.stringify({
		~~省略~~
	}),
});

まとめ

react-native-configはモバイルアプリのネイティブに直接埋め込みを可能にしているので、このままリリースするにはリスクが高すぎます(基本的にAPIキーはサーバー管理)。しかし、開発初期段階で素早く検証するには便利なライブラリですね。

ちなみに似たライブラリにreact-native-dotenvがありますが、主にWebをターゲットにする場合用いられるようです。時間があればそちらも記事にしたいと思います。

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?