DEV Community

Paul Robertson
Paul Robertson

Posted on

Your First AI API Integration in 10 Minutes: Build a Smart Text Summarizer

This article contains affiliate links. I may earn a commission at no extra cost to you.


title: "Your First AI API Integration in 10 Minutes: Build a Smart Text Summarizer"
published: true
description: "Learn to integrate OpenAI's API into a web app with practical examples and error handling"
tags: ai, tutorial, beginners, api, javascript

cover_image:

Your First AI API Integration in 10 Minutes: Build a Smart Text Summarizer

AI APIs have made it surprisingly easy to add intelligent features to your applications. Instead of training models from scratch, you can leverage pre-built APIs to handle complex tasks like text summarization, translation, or content generation.

In this tutorial, we'll build a practical text summarizer using OpenAI's API. You'll learn the fundamentals of AI API integration, proper error handling, and deployment basics. By the end, you'll have a working web app and the knowledge to expand it further.

What You'll Build

A simple web interface where users can paste long text and get AI-generated summaries. We'll use vanilla JavaScript to keep things straightforward, but the concepts apply to any framework.

Prerequisites

  • Basic JavaScript knowledge
  • Node.js installed on your machine
  • A text editor
  • 10 minutes of focused time

Step 1: Set Up OpenAI API Access

First, you'll need an OpenAI account and API key:

  1. Visit platform.openai.com and create an account
  2. Navigate to API Keys in your dashboard
  3. Click "Create new secret key" and copy it immediately
  4. Store it securely - you won't see it again

Important: Never commit API keys to version control. We'll use environment variables to keep them safe.

Step 2: Project Setup

Create a new directory and initialize your project:

mkdir ai-summarizer
cd ai-summarizer
npm init -y
npm install openai dotenv express
Enter fullscreen mode Exit fullscreen mode

Create a .env file in your project root:

OPENAI_API_KEY=your_api_key_here
Enter fullscreen mode Exit fullscreen mode

Add .env to your .gitignore file:

node_modules/
.env
Enter fullscreen mode Exit fullscreen mode

Step 3: Build the Summarization Function

Create server.js with your core AI integration:

require('dotenv').config();
const express = require('express');
const OpenAI = require('openai');

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

// Initialize OpenAI client
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

app.use(express.json());
app.use(express.static('public'));

// Summarization function with error handling
async function summarizeText(text) {
  try {
    // Input validation
    if (!text || text.trim().length < 50) {
      throw new Error('Text must be at least 50 characters long');
    }

    if (text.length > 4000) {
      throw new Error('Text too long. Please limit to 4000 characters.');
    }

    const response = await openai.chat.completions.create({
      model: "gpt-3.5-turbo",
      messages: [
        {
          role: "system",
          content: "You are a helpful assistant that creates concise, accurate summaries. Keep summaries to 2-3 sentences and focus on the main points."
        },
        {
          role: "user",
          content: `Please summarize this text: ${text}`
        }
      ],
      max_tokens: 150,
      temperature: 0.3, // Lower temperature for more consistent summaries
    });

    return response.choices[0].message.content.trim();
  } catch (error) {
    console.error('Summarization error:', error);

    // Handle different types of errors
    if (error.code === 'insufficient_quota') {
      throw new Error('API quota exceeded. Please try again later.');
    }

    if (error.code === 'invalid_api_key') {
      throw new Error('Invalid API configuration.');
    }

    throw error;
  }
}

// API endpoint
app.post('/api/summarize', async (req, res) => {
  try {
    const { text } = req.body;
    const summary = await summarizeText(text);
    res.json({ success: true, summary });
  } catch (error) {
    res.status(400).json({ 
      success: false, 
      error: error.message 
    });
  }
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Create the Web Interface

Create a public directory and add index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Text Summarizer</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        .container {
            background: #f8f9fa;
            padding: 30px;
            border-radius: 8px;
            margin: 20px 0;
        }
        textarea {
            width: 100%;
            min-height: 200px;
            padding: 15px;
            border: 2px solid #e9ecef;
            border-radius: 4px;
            font-size: 16px;
            resize: vertical;
        }
        button {
            background: #007bff;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            margin-top: 10px;
        }
        button:hover {
            background: #0056b3;
        }
        button:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }
        .result {
            margin-top: 20px;
            padding: 20px;
            background: white;
            border-radius: 4px;
            border-left: 4px solid #28a745;
        }
        .error {
            border-left-color: #dc3545;
            background: #f8d7da;
        }
        .loading {
            color: #6c757d;
        }
    </style>
</head>
<body>
    <h1>AI Text Summarizer</h1>
    <p>Paste your text below and get an AI-generated summary in seconds.</p>

    <div class="container">
        <textarea 
            id="textInput" 
            placeholder="Paste your text here (minimum 50 characters)..."
        ></textarea>

        <button id="summarizeBtn" onclick="summarizeText()">
            Summarize Text
        </button>

        <div id="result"></div>
    </div>

    <script>
        async function summarizeText() {
            const textInput = document.getElementById('textInput');
            const button = document.getElementById('summarizeBtn');
            const result = document.getElementById('result');

            const text = textInput.value.trim();

            if (!text) {
                showResult('Please enter some text to summarize.', true);
                return;
            }

            // Show loading state
            button.disabled = true;
            button.textContent = 'Summarizing...';
            showResult('Generating summary...', false, true);

            try {
                const response = await fetch('/api/summarize', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ text }),
                });

                const data = await response.json();

                if (data.success) {
                    showResult(data.summary, false);
                } else {
                    showResult(data.error, true);
                }
            } catch (error) {
                showResult('Network error. Please check your connection and try again.', true);
            } finally {
                button.disabled = false;
                button.textContent = 'Summarize Text';
            }
        }

        function showResult(message, isError = false, isLoading = false) {
            const result = document.getElementById('result');
            result.innerHTML = `<div class="result ${isError ? 'error' : ''} ${isLoading ? 'loading' : ''}">${message}</div>`;
        }

        // Allow Enter key to trigger summarization
        document.getElementById('textInput').addEventListener('keydown', function(e) {
            if (e.ctrlKey && e.key === 'Enter') {
                summarizeText();
            }
        });
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 5: Test Your Application

Start your server:

node server.js
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 and test with sample text. Try pasting a news article or blog post to see the summarization in action.

Step 6: Deploy Your App

For quick deployment, use a service like Render or Railway:

  1. Push your code to GitHub (remember to exclude .env)
  2. Connect your repository to your deployment service
  3. Add your OPENAI_API_KEY as an environment variable in the deployment settings
  4. Deploy and test

Common Issues and Solutions

"Invalid API Key" Error: Double-check your API key is correctly set in the environment variable and hasn't expired.

Rate Limiting: OpenAI has usage limits. Implement request queuing or user rate limiting for production apps.

Long Response Times: API calls can take 2-5 seconds. Always show loading states to users.

Token Limits: GPT-3.5-turbo has a 4,096 token limit (roughly 3,000 words). Validate input length before sending requests.

Next Steps

Now that you have a working AI integration, consider these enhancements:

  • Add different summary lengths: Let users choose brief, medium, or detailed summaries
  • Support multiple languages: OpenAI models work well with many languages
  • Implement caching: Store summaries to avoid re-processing identical text
  • Add user authentication: Track usage and provide personalized features
  • Try other AI tasks: Sentiment analysis, translation, or content generation

Conclusion

You've successfully built your first AI-powered application! The key takeaways are proper error handling, input validation, and user experience considerations. AI APIs are powerful tools, but they require thoughtful integration to create reliable applications.

The pattern you've learned here - authenticate, validate input, call API, handle errors, display results - applies to most AI integrations. Whether you're using OpenAI, Anthropic's Claude API, or Hugging Face models, the fundamentals remain the same.

Start experimenting with different prompts and parameters to see how they affect your results. The best way to learn AI integration is through hands-on practice.


Tools mentioned:

Top comments (0)