Artificial Intelligence is revolutionising web development, and integrating OpenAI’s GPT API into your React application can open up a world of interactive, intelligent features. In this article, you’ll learn how to set up a basic React app and connect it with the OpenAI API to make your first AI-powered request.
🛠️ What We’ll Build
A simple React app with an input field where users can enter a prompt and get a response from OpenAI’s GPT model.
🧰 Tools Needed
- React (Create React App or Vite)
- OpenAI API Key
- Axios or fetch for making HTTP requests
🔧 Step 1: Set Up the React App
If you don’t already have a React app, start one:
npx create-react-app openai-react-app cd openai-react-app npm start
Install Axios for easier HTTP requests:
npm install axios
🔑 Step 2: Get Your OpenAI API Key
- Go to OpenAI
- Sign in and generate a new API key
- Copy and store it safely — you’ll need it soon
Create a .env
file in your project root:
REACT_APP_OPENAI_API_KEY=your_openai_key_here
⚠️ Never commit your API key to GitHub.
🧠 Step 3: Create a GPT Request Function
In a new file api/openai.js
:
import axios from 'axios'; const apiKey = process.env.REACT_APP_OPENAI_API_KEY; export const getGPTResponse = async (prompt) => { try { const response = await axios.post( 'https://api.openai.com/v1/chat/completions', { model: 'gpt-3.5-turbo', messages: [{ role: 'user', content: prompt }], }, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json', }, } ); return response.data.choices[0].message.content; } catch (error) { console.error('Error from OpenAI:', error); return 'Something went wrong...'; }
💬 Step 4: Build the UI Component
In App.js
:
import React, { useState } from 'react'; import { getGPTResponse } from './api/openai'; function App() { const [prompt, setPrompt] = useState(''); const [response, setResponse] = useState(''); const handleSubmit = async () => { const reply = await getGPTResponse(prompt); setResponse(reply); }; return ( <div style={{ padding: 20 }}> <h2>Ask GPT Anything</h2> <textarea value={prompt} onChange={(e) => setPrompt(e.target.value)} rows={4} cols={50} placeholder="Type your prompt here..." /> <br /> <button onClick={handleSubmit}>Submit</button> <div style={{ marginTop: 20 }}> <strong>Response:</strong> <p>{response}</p> </div> </div> ); } export default App;
✅ Test It Out
Run your app, type a prompt like “What is React?”, and see GPT respond in real-time.
💡 Tips
- You can customise model parameters like temperature, max_tokens, and frequency_penalty to fine-tune the kind of responses you get.
- OpenAI’s GPT API is not free for ongoing use. You’ll need to set up a paid plan to continue using the service beyond any free trial credits.
As of now, OpenAI offers a pay-as-you-go pricing model. For example:
GPT-3.5-turbo: around $0.0015 per 1K input tokens and $0.002 per 1K output tokens.
GPT-4 and GPT-4-turbo cost more, and are typically used for more advanced use cases.
You can view full pricing details and monitor your usage in the OpenAI Pricing Dashboard.
⚠️ Be sure to set usage limits in your account settings to avoid unexpected charges.
Top comments (0)