Quick Guide to AI APIs

Futuristic AI themed tech image

Written by

in

This post will introduce the OpenAI, Gemini, and Anthropic Claude APIs, with setup and a very simple script in TypeScript.

Note: you can program against these APIs in TypeScript, JavaScript, Python, and many other languages.

Here are the current API getting started documentation pages. If the links break in the future due to changes in their documentation, please let us know via a comment.

OpenAI Quickstart

Gemini Quickstart

Claude Quickstart

Create a Developer Account and Configure Billing (and Spending Limits!)

Before running any code in your workspace, you need to create developer accounts for OpenAI, Gemini and Claude, and configure billing for each. Some providers offer a free tier.

OpenAI Billing Page

Gemini Billing Page

Claude Billing Page

Prevent Unexpected Usage Costs

Every programmatic request sends tokens to a remote AI service. Those requests can create real costs billed to your API accounts.

Before running automation, protect yourself with these safeguards:

Set Hard Usage Caps

Log into each provider’s billing dashboard and set aggressive daily or monthly budget limits, such as $5.00.

This can help prevent runaway scripts from draining credits or creating unexpected bills.

Avoid Production Models for Sandbox Loops

For simple tests, debugging, or CI loops, use cheaper, faster models when possible.

For example:

gemini-3.5-flash

Save larger, enterprise-grade models for targeted production use.

Guard Your Loops

When executing asynchronous requests, such as fetching paginated resources, polling for status changes, or executing retries—never use unbounded loops (while (true)) or raw condition-only loops. Instead, always enforce an explicit, hard-coded safety ceiling using a strict counter loop.

For example:

const MAX_API_ATTEMPTS = 5;

for (let attempt = 0; attempt < MAX_API_ATTEMPTS; attempt++) {
    // 1. Await your async API call or background operation
    const response = await fetchNextPayload();
    
    // 2. Evaluate target condition to break early if successful
    if (response.isComplete) {
        break; 
    }
    
    // Optional: Handle backoff/delay between attempts
}

This helps prevent infinite async loops from continuously hitting API endpoints.

Legal Disclaimer

The source code and implementation instructions in this guide are intended strictly for educational, informational, and prototyping purposes.

The author provides these materials “as is” without any express or implied warranties.

By executing the code in this workspace, you acknowledge that you are solely responsible for your developer accounts, API key security, financial liabilities, costs, and data usage charges incurred through your API keys or infrastructure.

The author shall not be held liable for direct, indirect, incidental, special, or consequential damages, including financial losses, unexpected credit usage, account suspension, or billing spikes.

Use responsibly and configure hard billing limits before running automation.

TypeScript Dev Environment

Before writing code for OpenAI, Gemini, or Claude, set up a clean TypeScript development environment.

TypeScript does not run directly on your computer without a compilation or translation step. To keep this quick start simple, this workspace uses tsx, which lets you execute .ts scripts instantly without manually building JavaScript files first.

Step 1: Initialize Your Node.js Workspace

First install Node.js if you do not have it already:

Node.js download page

After Node.js is installed, open your terminal, create a fresh project directory, move into it, and do an npm init:

mkdir ai-quickstarts && cd ai-quickstarts
npm init -y

This creates a default package.json file in your project root.

Step 2: Configure Modern ESM Modules

By default, Node.js uses the older CommonJS module system.

Modern AI SDKs and TypeScript code typically use clean import and export statements, so configure the project to use ECMAScript Modules, or ESM.

Open the generated package.json file and replace the entire file contents with this:

{

  "name": "ai-quickstarts",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start:openai": "tsx src/openai-test.ts",
    "start:gemini": "tsx src/gemini-test.ts",
    "start:claude": "tsx src/claude-test.ts"
  }
}

Step 3: Install SDKs and TypeScript Utilities

Install the core AI SDKs:

npm install openai@latest @google/genai@latest @anthropic-ai/sdk@latest

Install the development tools:

npm install -D typescript@latest tsx@latest @types/node@latest

What Is tsx?

tsx stands for TypeScript Execute.

Instead of manually compiling .ts files into a separate JavaScript output folder, tsx runs TypeScript files directly by stripping TypeScript-only syntax in memory.

This keeps the workflow fast and simple for quick API experiments.

Step 4: Create tsconfig.json

Generate a TypeScript config file:

npx tsc --init

This creates a tsconfig.json file in the project root.

Replace the entire default contents of this file with this clean baseline configuration:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"]
}

Step 5: Create the Project Structure

Create a src folder for your TypeScript files. Your project should look like this:

ai-quickstarts/
  ├── src/
  │ ├── openai-test.ts
  │ ├── gemini-test.ts
  │ └── claude-test.ts
  ├── package.json
  └── tsconfig.json

Create the three TypeScript files in the src directory and paste the following provider-specific quickstart code into the files:

File 1: src/openai-test.ts

This example uses OpenAI’s Responses API. It extracts the model output using the output_text helper property.

import OpenAI from "openai";

// Automatically extracts process.env.OPENAI_API_KEY
const client = new OpenAI();

async function main() {
  try {
    const response = await client.responses.create({
      model: "gpt-5.5",
      input: "Write a one-sentence bedtime story about a unicorn."
    });

    // The Responses API uses output_text to aggregate tokens
    console.log("OpenAI Response:");
    console.log(response.output_text);
  } catch (error) {
    console.error("OpenAI Execution Error:", error);
  }
}

main();

File 2: src/gemini-test.ts

This example uses the modern Google Gen AI SDK, @google/genai. It accesses the generated text through response.text.

import { GoogleGenAI } from "@google/genai";

// Automatically extracts process.env.GEMINI_API_KEY
const ai = new GoogleGenAI({});

async function main() {
  try {
    const response = await ai.models.generateContent({
      model: "gemini-3.5-flash",
      contents: "Write a one-sentence bedtime story about a unicorn."
    });

    // Prototype getter dynamically parses the inner JSON array
    console.log("Gemini Response:");
    console.log(response.text);
  } catch (error) {
    console.error("Gemini Execution Error:", error);
  }
}

main();

File 3: src/claude-test.ts

This example uses Anthropic’s structured Messages API.
Claude requests require an explicit max_tokens value. The response content is returned as an array of content blocks, so this script checks the first block before printing its text.

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

// Automatically extracts process.env.ANTHROPIC_API_KEY
const client = new Anthropic();

async function main() {
  try {
    const message = await client.messages.create({
      model: "claude-opus-4-8",
      max_tokens: 1000, // Required safety parameter
      messages: [
        {
          role: "user",
          content: "Write a one-sentence bedtime story about a unicorn."
        }
      ]
    });

    // Can return text, layout blocks, and tool executions.
    // Drill into the item array block to grab the text.
    console.log("Claude Response:");
    if (message.content[0].type === "text") {
      console.log(message.content[0].text);
    }
  } catch (error) {
    console.error("Anthropic Execution Error:", error);
  }
}

main();

Step 6: Configure Environment Variables

All three SDKs can read API credentials from your operating system environment. That means you DO NOT need to hardcode secret keys inside your code.

If fact, you should not hard code your API keys or any other sensitive information in code files or in any other files that might be committed to source control such as git.

You create an API key for each of these three APIs. Refer to the developer documentation for each of these APIs for instructions on creating API keys.

Note that when creating API keys you need to copy them somewhere on your computer, because after they are created you cannot view them again.

Run these commands in your active terminal session before executing the scripts, replacing the dummy values here with your actual API keys:

export OPENAI_API_KEY="sk-proj-..."
export GEMINI_API_KEY="AIzaSy..."
export ANTHROPIC_API_KEY="sk-ant-..."

Note that to avoid having to export the API keys every time you can place export statements in .bash_profile for example on Linux, or in the appropriate place for your operating system. Ask ChatGPT or the Gemini or Claude web chat interfaces if you are unsure how to do this.

Step 7: Execute the Scripts

With your variables loaded and your scripts mapped in package.json, run each provider test independently.

To better compare the result, execute each in a separate terminal shell window.

# Execute the OpenAI Responses API script

npm run start:openai

# Execute the Google Gemini Gen AI script

npm run start:gemini

# Execute the Claude Anthropic Messages script

npm run start:claude

Note: these three scripts use the same prompt but generate different results, because they use an LLM (Large Language Model, the AI brain) specific to the API.

Write a one-sentence bedtime story about a unicorn.

Your results will likely differ from the following:

OpenAI Response:

Under a moonlit sky, a gentle unicorn sprinkled stardust over the sleepy forest so every creature could dream of magic until morning.

Gemini Response:

As the silver moon climbed high, the little unicorn tucked her hooves beneath a blanket of stardust, rested her weary head, and let the magic of her glowing horn fade gently into a quiet night of sweet dreams.

Claude Response:

Beneath a blanket of twinkling stars, a gentle unicorn named Luna pranced across meadows of moonlit clover, sprinkling sweet dreams into the hearts of all the sleeping children below.

Final thoughts…

This workspace is intended for simple API learning and experimentation.

Before running these scripts:

– Confirm your API keys are configured.

– Set hard billing limits.

– Keep test loops small.

– Avoid hardcoding secrets.

– Use lower-cost models for sandbox work.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *