This section guides you through using Express to securely make API calls to OpenAI's GPT-3.5-turbo model, receive JSON results, and parse them.
node-fetch
package installed for using Fetch API in Node.js.Environment Setup:
node-fetch
using npm install node-fetch
.OPENAI_API_KEY
).Creating an Express Route:
const express = require('express');
const fetch = require('node-fetch');
const app = express();
app.get('/api/gpt', async (req, res) => {
// API call will be made here
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Making an API Call to OpenAI:
app.get('/api/gpt', async (req, res) => {
try {
const response = await fetch('<https://api.openai.com/v1/engines/gpt-3.5-turbo/completions>', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
},
body: JSON.stringify({ prompt: "Translate the following English text to French: 'Hello, world!'", max_tokens: 60 })
});
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const data = await response.json();
res.json(data);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
Running the Server:
http://localhost:3000/api/gpt
) to make the API call.