DEV Community

Cover image for Integrating OpenAI API with a React Application
Jehnsen Enrique
Jehnsen Enrique

Posted on • Edited on

Integrating OpenAI API with a React Application

In today's tech landscape, integrating powerful AI tools into web applications can significantly enhance user experience and functionality. One such tool is OpenAI's API, which can bring advanced language processing capabilities to your React applications. In this blog post, we'll walk through the process of integrating OpenAI with a React app step by step.

Prerequisites
Before we start, ensure you have the following:

  • Node.js and npm: Ensure you have Node.js installed, which comes with npm.
  • React Application: A basic React application setup.
  • OpenAI API Key: Sign up at OpenAI and get your API key.

Step 1: Set Up Your React App
If you don't already have a React app, you can create one using create-react-app:

npx create-react-app openai-react-app
cd openai-react-app
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Axios
We'll use Axios for making HTTP requests to the OpenAI API. Install Axios using npm:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Step 3: Create OpenAI Service
Create a new file called openaiService.js in the src directory of your React app. This file will handle the API requests to OpenAI.

// src/openaiService.js

import axios from 'axios';

const API_KEY = 'YOUR_OPENAI_API_KEY';

const openai = axios.create({
  baseURL: 'https://api.openai.com/v1',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${API_KEY}`,
  },
});

export const getOpenAIResponse = async (prompt) => {
  const response = await openai.post('/completions', {
    model: 'text-davinci-003',
    prompt: prompt,
    max_tokens: 100,
  });
  return response.data;
};

Enter fullscreen mode Exit fullscreen mode

Replace YOUR_OPENAI_API_KEY with your actual OpenAI API key.

Step 4: Create a Component to Use OpenAI
Next, create a new component that will use the getOpenAIResponse function to fetch data from OpenAI.

// src/components/OpenAIComponent.js

import React, { useState } from 'react';
import { getOpenAIResponse } from '../openaiService';

const OpenAIComponent = () => {
  const [input, setInput] = useState('');
  const [response, setResponse] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    const aiResponse = await getOpenAIResponse(input);
    setResponse(aiResponse.choices[0].text);
  };

  return (
    <div>
      <h1>OpenAI Integration with React</h1>
      <form onSubmit={handleSubmit}>
        <textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          rows="5"
          cols="50"
          placeholder="Type your prompt here..."
        />
        <br />
        <button type="submit">Get Response</button>
      </form>
      <div>
        <h2>Response:</h2>
        <p>{response}</p>
      </div>
    </div>
  );
};

export default OpenAIComponent;

Enter fullscreen mode Exit fullscreen mode

Step 5: Integrate the Component into Your App
Finally, integrate the OpenAIComponent into your main application file (App.js).

// src/App.js

import React from 'react';
import OpenAIComponent from './components/OpenAIComponent';

function App() {
  return (
    <div className="App">
      <OpenAIComponent />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 6: Run Your React App
Run your React application to see the integration in action:

npm start
Enter fullscreen mode Exit fullscreen mode

Conclusion
By following these steps, you have successfully integrated OpenAI's API with a React application. This setup allows you to leverage OpenAI's powerful language models to generate responses based on user input, opening up a world of possibilities for enhancing user experiences. Whether you're building a chatbot, a writing assistant, or any other AI-powered feature, this integration provides a solid foundation to start from.

Feel free to experiment further and customize the integration to suit your specific needs. Happy coding!

Additional Resources
OpenAI API Documentation
React Documentation
Axios Documentation
If you have any questions or need further assistance, feel free to leave a comment below.

Top comments (0)