Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using OpenAI API with JavaScript

Introduction

This tutorial demonstrates how to integrate and use the OpenAI API with JavaScript to leverage powerful AI capabilities in your web applications.

1. Setting Up Your OpenAI API Key

Before getting started, ensure you have your OpenAI API key ready. You can obtain it from the OpenAI website after signing up for an account.

2. Making API Requests

To make requests to the OpenAI API using JavaScript, you'll use tools like fetch or Axios. Here are examples of different API requests:

2.1 Text Completion Example

Example of completing text using the API:

fetch('https://api.openai.com/v1/completions', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_KEY_HERE'
    },
    body: JSON.stringify({
        prompt: "Translate English to French: Hello, how are you?",
        max_tokens: 50
    })
})
.then(response => response.json())
.then(data => {
    console.log(data.choices[0].text);
})
.catch(error => console.error('Error:', error));
                    

Output (console log): "Bonjour, comment vas-tu ?"

2.2 Image Captioning Example

Example of generating a caption for an image:

fetch('https://api.openai.com/v1/images/caption', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_API_KEY_HERE'
    },
    body: JSON.stringify({
        image: 'URL_TO_YOUR_IMAGE'
    })
})
.then(response => response.json())
.then(data => {
    console.log(data.caption);
})
.catch(error => console.error('Error:', error));
                    

Output (console log): "A dog running in the park"

3. Handling Responses

Once you receive a response from the API, you can handle it in your JavaScript code. Here’s how you might handle the completion response:

// Assuming 'data' contains the API response
console.log(data.choices[0].text);
                    

In this example, data.choices[0].text contains the translated text returned by the OpenAI API.

Conclusion

Integrating the OpenAI API with JavaScript allows you to incorporate advanced AI functionalities into your web applications. Explore more API endpoints and capabilities to enhance your projects.