bullseye-arrowQuickstart

How to integrate ai api in your app.

1. API Integration Example: Using OpenAI API for Text Generation (e.g., ChatGPT)

To integrate a generative AI API into your app, you'll follow these steps:

Step 1: Setup Your Environment

  • Sign up for the OpenAI API (or any other AI API provider).

  • Get your API key from the API provider, which you'll use to authenticate requests.

Step 2: Create the App

You can create a simple web app where users input prompts, and the app generates text responses using the API. Below is an example using Node.js for the backend and OpenAI’s GPT for generating text.

Example: Simple App Flow

  • Frontend: A form where users enter text prompts.

  • Backend: Receives the prompt and forwards it to the OpenAI API.

  • AI Model: The API processes the prompt and returns the generated text.

  • Response: The backend returns the generated text to the frontend, which displays it.

2. Example Code: Integrating AI API (Next.js + OpenAI)

Frontend (Next.js Page)

This page allows the user to submit a prompt and see the AI-generated text response.

Create a file app/index.js:

"use client"
import { useState } from 'react';

export default function Home() {
  const [prompt, setPrompt] = useState('');
  const [result, setResult] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);

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

    const data = await response.json();
    setResult(data.generatedText);
    setLoading(false);
  };

  return (
    <div style={{ padding: '20px' }}>
      <h1>AI Text Generator</h1>
      <form onSubmit={handleSubmit}>
        <label htmlFor="prompt">Enter a prompt:</label>
        <input
          type="text"
          id="prompt"
          value={prompt}
          onChange={(e) => setPrompt(e.target.value)}
          required
          style={{ marginLeft: '10px' }}
        />
        <button type="submit" style={{ marginLeft: '10px' }}>
          Generate
        </button>
      </form>
      {loading ? <p>Loading...</p> : <p>{result}</p>}
    </div>
  );
}

API Route (Next.js API Endpoint)

In Next.js, you can create API routes to handle requests.

Create a file app/api/generate.js:

Environment Variables

In Next.js, environment variables are defined in a .env.local file.

Create a .env.local file in the root of your project:

3. How It Works

  1. User Input:

    • The user enters a prompt in the text input on the frontend (e.g., “Explain AI in simple terms”).

  2. Send Request:

    • When the form is submitted, the handleSubmit function sends a POST request to the /api/generate API route with the prompt.

  3. API Route:

    • The API route (app/api/generate.js) receives the request, forwards the prompt to the OpenAI API, and fetches the generated text.

  4. OpenAI Response:

    • The OpenAI API processes the request and returns the generated text (e.g., "AI stands for artificial intelligence...").

  5. Return Result:

    • The API route sends the generated text back to the frontend, where it is displayed to the user.

4. API Endpoint Documentation

Here’s a breakdown of the API endpoint:

  • Endpoint: /api/generate

  • Method: POST

  • Request:

Request

Body (JSON):

Response:

  • Success (200)

Error (500):

  1. Running the App

Access the app: Open your browser and navigate to http://localhost:3000. Enter a prompt in the input box and see the AI-generated response displayed below the form.

Last updated