Back to BlogAI Development

Building with AI APIs: A Developer's Guide

MiloDecember 8, 202515 min read
Building with AI APIs: A Developer's Guide

Building with AI APIs: A Developer's Guide

Ready to add AI to your applications? This guide covers the major AI APIs and how to use them effectively.

Overview of Major AI APIs

Text/Chat APIs

ProviderModelsBest For
OpenAIGPT-4, GPT-3.5General purpose
AnthropicClaude 3Long context, safety
GoogleGeminiMultimodal
CohereCommandEnterprise

Image APIs

ProviderModelsBest For
OpenAIDALL-E 3Quality, accuracy
Stability AISDXLCustomization
MidjourneyMJ APIAesthetics

Voice APIs

ProviderFeaturesBest For
ElevenLabsTTS, cloningQuality voices
OpenAIWhisper, TTSTranscription
AssemblyAITranscriptionAccuracy

Getting Started with OpenAI

Setup

npm install openai

Basic Chat Completion

import OpenAI from 'openai';

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

async function chat(message) {
  const completion = await openai.chat.completions.create({
    model: "gpt-4",
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: message }
    ],
  });
  
  return completion.choices[0].message.content;
}

Streaming Responses

async function streamChat(message) {
  const stream = await openai.chat.completions.create({
    model: "gpt-4",
    messages: [{ role: "user", content: message }],
    stream: true,
  });
  
  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content || "");
  }
}

Anthropic Claude API

Setup

npm install @anthropic-ai/sdk

Basic Usage

import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

async function askClaude(message) {
  const response = await anthropic.messages.create({
    model: "claude-3-sonnet-20250229",
    max_tokens: 1024,
    messages: [
      { role: "user", content: message }
    ],
  });
  
  return response.content[0].text;
}

Image Generation

DALL-E 3

async function generateImage(prompt) {
  const response = await openai.images.generate({
    model: "dall-e-3",
    prompt: prompt,
    n: 1,
    size: "1024x1024",
    quality: "hd",
  });
  
  return response.data[0].url;
}

Stability AI

async function generateWithStability(prompt) {
  const response = await fetch(
    "https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/text-to-image",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${process.env.STABILITY_API_KEY}`,
      },
      body: JSON.stringify({
        text_prompts: [{ text: prompt }],
        cfg_scale: 7,
        steps: 30,
      }),
    }
  );
  
  const data = await response.json();
  return data.artifacts[0].base64;
}

Best Practices

Error Handling

async function safeAPICall(fn) {
  try {
    return await fn();
  } catch (error) {
    if (error.status === 429) {
      // Rate limited - implement backoff
      await sleep(1000);
      return safeAPICall(fn);
    }
    if (error.status === 500) {
      // Server error - retry
      return safeAPICall(fn);
    }
    throw error;
  }
}

Cost Management

// Track token usage
function trackUsage(response) {
  const usage = response.usage;
  console.log(`Tokens: ${usage.total_tokens}`);
  console.log(`Cost: $${(usage.total_tokens / 1000) * 0.03}`);
}

Caching

const cache = new Map();

async function cachedChat(message) {
  const key = hashMessage(message);
  
  if (cache.has(key)) {
    return cache.get(key);
  }
  
  const response = await chat(message);
  cache.set(key, response);
  return response;
}

Building a Simple AI App

Example: AI Writing Assistant

import express from 'express';
import OpenAI from 'openai';

const app = express();
const openai = new OpenAI();

app.post('/api/improve-writing', async (req, res) => {
  const { text, style } = req.body;
  
  const completion = await openai.chat.completions.create({
    model: "gpt-4",
    messages: [
      {
        role: "system",
        content: `You are a writing assistant. Improve the given text to be more ${style}. Return only the improved text.`
      },
      { role: "user", content: text }
    ],
  });
  
  res.json({ improved: completion.choices[0].message.content });
});

app.listen(3000);

Pricing Comparison

ProviderModelInputOutput
OpenAIGPT-4$30/1M$60/1M
OpenAIGPT-3.5$0.50/1M$1.50/1M
AnthropicClaude 3 Sonnet$3/1M$15/1M
GoogleGemini Pro$0.50/1M$1.50/1M

Security Considerations

  1. Never expose API keys in client-side code
  2. Implement rate limiting to prevent abuse
  3. Validate inputs before sending to AI
  4. Filter outputs for sensitive content
  5. Log usage for monitoring and debugging
Milo

Milo

Milo covers AI coding tools and developer workflows for the Scout AI Team — the same agentic stack that builds and ships this site.

Building with AI APIs: A Developer's Guide | AIToolScout