1. OpenAI API Key 발급
- https://platform.openai.com 에 로그인
- API Keys 메뉴로 이동 https://platform.openai.com/settings/organization/api-keys
- 새 Key 생성 → 복사 (한 번만 보여짐)

2. 환경 변수에 API 키 저장
루트 디렉토리에 .env 파일 생성:
REACT_APP_OPENAI_API_KEY=내api키
.env 파일은 .gitignore에 포함되어야 합니다.
3. GPT API 호출 함수 작성 (openai.ts)
// src/api/openai.ts
import axios from 'axios';
const API_KEY = import.meta.env.VITE_OPENAI_API_KEY;
const API_URL = 'https://api.openai.com/v1/chat/completions';
export const sendMessageToGPT = async (message: string) => {
try {
const response = await axios.post(
API_URL,
{
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: message }],
},
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${API_KEY}`,
},
}
);
return response.data.choices[0].message.content;
} catch (error) {
console.error('GPT API 호출 오류:', error);
throw error;
}
};
*process 를 쓰려면 설치해주어야 한다.
나는 VITE를 써서 해주었는데 npx 로 만든 react일 경우에는
const API_KEY = import.meta.env.VITE_OPENAI_API_KEY; // VITE에서
REACT_APP_OPENAI_API_KEY=sk-xxxxx...
const API_KEY = process.env.REACT_APP_OPENAI_API_KEY;
로 해준다고 한다.
로 해준다고 한다.
4. React 컴포넌트에서 사용하기
테스트를 위해서 대~충 페이지 하나를 만들었다.
import { useState } from 'react';
import { sendMessageToGPT } from '../services/gpt/openai';
const Testpage = () => {
const [input, setInput] = useState('');
const [response, setResponse] = useState('');
const handleSubmit = async () => {
const result = await sendMessageToGPT(input);
setResponse(result);
};
return (
<div style={{ padding: 20 }}>
<h1>GPT와 대화하기</h1>
<textarea
rows={4}
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="메시지를 입력하세요"
/>
<br />
<button onClick={handleSubmit}>전송</button>
<h3>GPT 응답:</h3>
<p>{response}</p>
</div>
);
}
export default Testpage;
5. 429에러 해결하기


429 에러가 떠서 봤는데 무료가 안 되는 거 같다 ...

최소 결제 금액이 5.5달러 ㅠㅠ 커피 3잔 아낀다고 생각해서 결제했다.
찾아보니 다른 ai도 (claude 등) 완전히 무료인 api 호출 기능은 없는 것 같다.
6. 끗

'프론트엔드' 카테고리의 다른 글
| [FE] 축제 웹사이트 프론트엔드 회고 (0) | 2025.05.26 |
|---|---|
| [Github] 자동 merge Workflow 설정하기 (0) | 2025.05.26 |
| [FE] CSS 스크롤바 감추기 (0) | 2025.05.02 |
| [FE] 프론트엔드 클라이언트 배포 비교 (0) | 2025.03.15 |
| [FE] React(리액트) 라우팅과 Next.js 파일 기반 라우팅의 비교 (0) | 2024.10.05 |