How to Implement OpenAI API Key in a Node.js Express App

Rowsan Ali - Feb 27 - - Dev Community

In this blog post, we'll walk through the process of integrating the OpenAI API into a Node.js Express application. By the end of this tutorial, you'll be able to send requests to the OpenAI API from your Express app and receive responses that you can use to build intelligent features like chatbots, text summarization, and more.

If you're a developer or just starting out.
I recommend signing up for our free newsletter 'ACE Dev' .
It gets delivered to your inbox and includes actionable steps and helpful resources.
Join us now

Prerequisites

Before we begin, make sure you have the following installed:

  1. Node.js: You can download and install it from nodejs.org.
  2. npm: This comes bundled with Node.js.
  3. Express: We'll use this to create our web server.
  4. OpenAI API Key: You can get this by signing up at OpenAI.

Step 1: Set Up Your Node.js Express App

First, let's create a new Node.js project and set up an Express server.

mkdir openai-express-app
cd openai-express-app
npm init -y
npm install express axios dotenv
Enter fullscreen mode Exit fullscreen mode
  • express: To create the web server.
  • axios: To make HTTP requests to the OpenAI API.
  • dotenv: To manage environment variables, including your OpenAI API key.

Step 2: Create the Express Server

Create a file named index.js and set up a basic Express server.

// index.js
const express = require('express');
const axios = require('axios');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());

app.get('/', (req, res) => {
  res.send('Hello, OpenAI!');
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Store Your OpenAI API Key

Create a .env file in the root of your project to store your OpenAI API key.

# .env
OPENAI_API_KEY=your_openai_api_key_here
PORT=3000
Enter fullscreen mode Exit fullscreen mode

Make sure to replace your_openai_api_key_here with your actual OpenAI API key.

Step 4: Create an Endpoint to Interact with OpenAI

Now, let's create an endpoint that will send a request to the OpenAI API and return the response.

// index.js
app.post('/ask', async (req, res) => {
  const { prompt } = req.body;

  if (!prompt) {
    return res.status(400).json({ error: 'Prompt is required' });
  }

  try {
    const response = await axios.post(
      'https://api.openai.com/v1/completions',
      {
        model: 'text-davinci-003', // You can use other models like 'gpt-3.5-turbo'
        prompt: prompt,
        max_tokens: 150,
        temperature: 0.7,
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
        },
      }
    );

    res.json({ response: response.data.choices[0].text.trim() });
  } catch (error) {
    console.error('Error calling OpenAI API:', error);
    res.status(500).json({ error: 'An error occurred while processing your request' });
  }
});
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • POST /ask: This endpoint accepts a JSON payload with a prompt field.
  • axios.post: We use Axios to send a POST request to the OpenAI API.
  • model: We're using the text-davinci-003 model, but you can choose other models depending on your needs.
  • prompt: This is the input text that you want to send to the OpenAI API.
  • max_tokens: This limits the length of the response.
  • temperature: This controls the creativity of the response. Lower values make the response more deterministic, while higher values make it more creative.

Step 5: Test Your Endpoint

You can test your endpoint using a tool like Postman or cURL.

Example cURL Request:

curl -X POST http://localhost:3000/ask \
-H "Content-Type: application/json" \
-d '{"prompt": "What is the capital of France?"}'
Enter fullscreen mode Exit fullscreen mode

Example Response:

{
  "response": "The capital of France is Paris."
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Deploy Your App

Once you've tested your app locally, you can deploy it to a cloud service like Heroku, Vercel, or AWS.

Example Deployment to Heroku:

  1. Install the Heroku CLI and log in.
  2. Create a new Heroku app:
   heroku create
Enter fullscreen mode Exit fullscreen mode
  1. Add your .env variables to Heroku:
   heroku config:set OPENAI_API_KEY=your_openai_api_key_here
Enter fullscreen mode Exit fullscreen mode
  1. Deploy your app:
   git push heroku main
Enter fullscreen mode Exit fullscreen mode
  1. Open your app:
   heroku open
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this tutorial, we've successfully integrated the OpenAI API into a Node.js Express app. You can now use this setup to build intelligent features powered by OpenAI's language models. Whether you're building a chatbot, a text summarization tool, or any other AI-powered application, the possibilities are endless.

Feel free to expand on this example by adding more endpoints, handling different types of prompts, or integrating with other APIs. Happy coding!

Full Code Example

Here's the complete code for reference:

// index.js
const express = require('express');
const axios = require('axios');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());

app.get('/', (req, res) => {
  res.send('Hello, OpenAI!');
});

app.post('/ask', async (req, res) => {
  const { prompt } = req.body;

  if (!prompt) {
    return res.status(400).json({ error: 'Prompt is required' });
  }

  try {
    const response = await axios.post(
      'https://api.openai.com/v1/completions',
      {
        model: 'text-davinci-003',
        prompt: prompt,
        max_tokens: 150,
        temperature: 0.7,
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
        },
      }
    );

    res.json({ response: response.data.choices[0].text.trim() });
  } catch (error) {
    console.error('Error calling OpenAI API:', error);
    res.status(500).json({ error: 'An error occurred while processing your request' });
  }
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

.env File:

OPENAI_API_KEY=your_openai_api_key_here
PORT=3000
Enter fullscreen mode Exit fullscreen mode

package.json Dependencies:

{
  "dependencies": {
    "express": "^4.17.1",
    "axios": "^0.21.1",
    "dotenv": "^10.0.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

If you're a developer or just starting out.
I recommend signing up for our free newsletter 'ACE Dev' .
It gets delivered to your inbox and includes actionable steps and helpful resources.
Join us now

That's it! You now have a fully functional Node.js Express app that interacts with the OpenAI API.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .