Section: Making Secure API Calls with Express and Fetch API

Objective

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.

Prerequisites

Steps

  1. Environment Setup:

  2. 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}`));
    
  3. 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 });
        }
    });
    
  4. Running the Server: