Table of Contents
From API Keys to Web Integration — A Hands‑on Guide to OpenAI, Anthropic Claude, and Amazon Bedrock
Today, we'll comprehensively cover how to integrate generative AI APIs into real web applications, explained in a tutorial format that's accessible even for beginners. We'll focus on the three main providers: OpenAI, Anthropic Claude, and Amazon Bedrock, following the sequence: key acquisition → authentication → minimal code examples → pricing considerations → operational tips.
Table of Contents
- Introduction: API Keys and Authentication Overview
- Universal Principles (Critical)
- OpenAI: Key Acquisition, Authentication, Minimal Code, Pricing
- Anthropic Claude: Key Acquisition, Authentication, Minimal Code, Pricing
- Amazon Bedrock: Credentials, Signing (SigV4), Minimal Code, Pricing
- Safe Integration Patterns for Web Apps (Next.js/Node examples)
- Rough Cost Estimation and Thinking
- Security and Operations Best Practices
- Summary
1. Introduction: API Keys and Authentication Overview
Let's start with terminology.
- API Key: A secret string issued by service providers (like OpenAI). When attached to HTTP request headers, it identifies "who you are" and is linked to billing and rate limiting (how many requests you can make within a certain time period).
- Authentication Methods:
- Bearer Token: Method using
Authorization: Bearer <API_KEY>in headers. Used by OpenAI and Anthropic. - AWS SigV4 Signature: AWS doesn't send keys directly but calculates a signature from access key ID/secret and attaches it to headers. Bedrock uses this (SDK handles it automatically). ([AWS Documentation][1])
Analogy:
API keys are like "hotel room keys," while SigV4 is like "ID card + signature book." The former gets you through by presentation, the latter verifies "the person actually signed it."
2. Universal Principles (Critical)
- Never expose API keys to the frontend (browser)!
Official documentation explicitly states "do not distribute keys to clients." Always route through your own backend. ([OpenAI Help Center][2])
- NG: Calling OpenAI directly from Next.js Client Components
- OK: Creating server routes like /api/generate and making requests to each provider from there
3. OpenAI
3-1. Key Acquisition
- Log into the official dashboard (platform.openai.com) → API Keys screen to issue keys. ([OpenAI Platform][3])
3-2. Authentication
- Add
Authorization: Bearer <OPENAI_API_KEY>to HTTP headers. - Official quickstart guides and SDK examples are comprehensive. ([OpenAI Platform][4])
3-3. Minimal Code (Node.js / Express example)
Note: Frontend only calls /api/openai-chat. Keys are stored on the server side.
// server.ts (Express)
import express from "express";
import fetch from "node-fetch";
const app = express();
app.use(express.json());
app.post("/api/openai-chat", async (req, res) => {
const { messages } = req.body; // [{role:'user', content:'...'}] etc.
const r = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer undefined`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-4.1", // Example: adjust model to requirements
messages,
temperature: 0.7,
}),
});
const data = await r.json();
res.json(data);
});
app.listen(3000);
3-4. Pricing Overview
- Input/output token prices are set per model. Always check the latest official "API Pricing" table. ([OpenAI][5])
- Additional tool charges like web search tools exist, so estimate during design phase based on usage. ([OpenAI][5])
Mini-knowledge: Tokens are word fragment units. Longer prompts and responses increase costs, so prompt shortening, system prompt standardization, and caching are effective.
4. Anthropic Claude (Claude API)
4-1. Key Acquisition
- Issue API keys at Claude Console (console.anthropic.com). Procedures are also organized in support articles. ([console.anthropic.com][6])
4-2. Authentication
- POST with
Authorization: Bearer <ANTHROPIC_API_KEY>andanthropic-versionheader (e.g.,2023-06-01).
4-3. Minimal Code (Node.js / Express)
app.post("/api/claude-chat", async (req, res) => {
const { messages } = req.body; // [{role:'user', content:'...'}]
const r = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"x-api-key": process.env.ANTHROPIC_API_KEY!, // Old: Authorization also works
"anthropic-version": "2023-06-01",
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-3-5-sonnet-20240620", // Example
max_tokens: 1024,
messages,
}),
});
res.json(await r.json());
});
4-4. Pricing Overview
- Representative model Claude 3.5 Sonnet API pricing is $3 input / $15 output (per million tokens). Features large context length (~200K). ([Anthropic][7])
- Plans (Free/Pro/Max/Team/Enterprise) and personal subscriptions are also published (separate from API but useful for decision-making). ([Claude][8])
- External price comparison guides are also helpful (always reconfirm latest with official sources). ([CloudZero][9])
Analogy:
Claude is a "long-text specialist consultant." Great for feeding entire manuals or meeting minutes for summarization and extraction, though output token prices vary by model.
5. Amazon Bedrock
5-1. Credentials (IAM) and Signing (SigV4)
- Using Bedrock via API requires AWS account authentication (IAM user/role) as the foundation. SDK automates SigV4 signing. ([AWS Documentation][1])
- As of 2025, Bedrock-specific API keys are also available (IAM Console → User → Security credentials → "API keys for Amazon Bedrock"). Choose based on organizational policies. ([AWS Documentation][10])
- IAM user access key creation procedures (traditional) are also officially documented. ([AWS Documentation][11])
5-2. Minimal Code (Node.js / AWS SDK v3)
import { BedrockRuntimeClient, InvokeModelCommand } from "@aws-sdk/client-bedrock-runtime";
const client = new BedrockRuntimeClient({
region: "us-east-1", // Match the model's available region
// Authentication uses default provider chain (environment variables, ~/.aws/credentials, roles, etc.)
});
app.post("/api/bedrock-chat", async (req, res) => {
const input = {
modelId: "anthropic.claude-3-5-sonnet-20240620-v1:0", // Example: always check available models in console
contentType: "application/json",
accept: "application/json",
body: JSON.stringify({
anthropic_version: "2023-06-01",
max_tokens: 1024,
messages: [{ role: "user", content: [{ type: "text", text: req.body.prompt }] }],
}),
};
const out = await client.send(new InvokeModelCommand(input));
res.type("json").send(Buffer.from(out.body!).toString("utf-8"));
});
5-3. Pricing Overview
- Input/output token prices differ by model provider, with three purchase options (on-demand/batch/provisioned throughput). ([Amazon Web Services, Inc.][12])
- Provisioned secures dedicated capacity at hourly rates (e.g., $39.60/hour per model unit... actual amounts vary by model×region, so always reconfirm with official sources). ([Cloudforecast][13])
Fun fact:
Bedrock's appeal is accessing multiple vendor models (Anthropic, Meta, Cohere, Mistral, etc.) through a unified API. Easy integration with AWS networks, permissions, and auditing is also valuable in practice.
6. Safe Integration Patterns for Web Apps (Next.js/Node examples)
6-1. Recommended Architecture (Minimal Setup)
[Browser] --fetch--> [/api/* (your backend)] --SDK/HTTPS--> [OpenAI/Claude/Bedrock]
↑ Various keys/AWS auth in .env
- Browser only calls your own API. External AI APIs are called from server side.
- Inject keys/authentication info as environment variables at deployment destinations (Vercel/AWS/ECS, etc.).
- Centralize monitoring, rate limiting, caching, and logging in your own API.
6-2. Next.js App Router Example (Edge/Node both work)
// app/api/generate/route.ts
import { NextRequest } from "next/server";
export async function POST(req: NextRequest) {
const { provider, messages } = await req.json();
switch (provider) {
case "openai":
// ... OpenAI fetch from above goes here
break;
case "claude":
// ... Anthropic fetch from above goes here
break;
case "bedrock":
// ... Bedrock SDK call from above goes here
break;
}
return new Response(JSON.stringify({}), { headers: { "Content-Type": "application/json" } });
}
- Frontend only uses
fetch("/api/generate", { method:"POST", body: JSON.stringify({...}) }). - No authentication info is exposed to client (re-emphasized). ([OpenAI Help Center][2])
7. Rough Cost Estimation and Thinking
7-1. Basic Formula
- Cost ≈ (Input token count × Input price) + (Output token count × Output price)
- For conversational use, estimate with "average tokens per round trip × expected monthly usage."
7-2. Specific Guidelines (Always reconfirm model prices with latest official tables)
- OpenAI: Prices vary by model. Please refer to the latest official pricing table (additional charges for web search and tools are also noted). ([OpenAI][5])
- Anthropic: For example, Claude 3.5 Sonnet is $3 input / $15 output / million tokens. Strong at long-text processing. ([Anthropic][7])
- Amazon Bedrock: Prices vary by model×region, and cost structure changes with on-demand/batch/provisioned selection. ([Amazon Web Services, Inc.][12])
Helper tools: Price calculation sites (like Helicone) let you input input/output tokens for quick comparison (but final decisions should use official pricing tables). ([Helicone.ai][14])
8. Security and Operations Best Practices
- Don't expose keys to clients (third emphasis). Also stated in official guides. ([OpenAI Help Center][2])
- Manage with environment variables: Keep
.envout of Git. Use secret management at deployment destinations (Vercel/AWS Secrets Manager/GHA Secrets, etc.). - Rate limiting: Implement throttling in your own API by IP/user. Include "key reissuance" in operational procedures as backup for potential leaks/abuse.
- Logs and personal information: Don't casually store full prompts/outputs. Use PII masking or summary logs.
- Cost guards:
- Start with "sufficiently cheap minimal setup" for validation → upgrade as needed
- Template optimization for inputs, output token limits are mandatory
- Caching (reusing identical prompts), tool usage charges also need separate management (OpenAI's web search tools, etc.). ([OpenAI][5])
- Cloud permissions (Bedrock): Design IAM with least privilege. Let SDK handle SigV4 and role operations. ([AWS Documentation][1])
9. Summary
- Key Points
- OpenAI/Anthropic use bearer keys, Bedrock uses AWS authentication (SigV4 or Bedrock API keys). ([AWS Documentation][1])
- Keys only on server side. Using Next.js/Express
/api/*as a relay is safe and easily extensible. ([OpenAI Help Center][2]) - Pricing is input/output token price multiplication + additional tools if needed. Make checking official pricing tables a habit. ([OpenAI][5])
- Which to choose? (Very roughly)
- OpenAI: Wide model ecosystem, abundant implementation examples.
- Claude: Strong at long text, effective for summarization, research, code review. ([Anthropic][7])
- Bedrock: Easy to integrate with AWS permissions and auditing, suitable for enterprises wanting to use multiple models through one interface. ([Amazon Web Services, Inc.][12])
Appendix: Reference Links (Official sources)
- OpenAI: API Pricing / Quickstart / API Keys (latest pricing and implementation) ([OpenAI][5])
- Anthropic: Claude 3.5 Sonnet pricing / Console / API access procedures (key issuance) ([Anthropic][7])
- AWS: SigV4 / Bedrock pricing / Bedrock API keys / IAM access key creation ([AWS Documentation][1])
Bonus: Minimal Frontend (React) Example
Frontend only calls your own API.
// example.tsx
const onAsk = async () => {
const res = await fetch("/api/openai-chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: "Hello" }] }),
});
const data = await res.json();
console.log(data);
};
Final word:
Start by creating minimal server routes, running with one model with production-level input/output limits. Next, implement cost monitoring and permissions, and finally model selection comparison. This approach balances development speed and safety.

NEW NOVEL 2026/08/01
Clouded Glass
Polishing is not about force.
Volume two of The World Became Slightly Farther Away.Five stories that can also be read as a starting point.
View on Amazon
Jijoden.com
Your life is worth writing.
There is a truer self you can tell only to AI.Gather fragments of memory into a single story.
Take a LookRelated Articles
OpenAI Reaches Pentagon Agreement While Anthropic Faces Exclusion? Verification and Implications (As of March 4, 2026)
A source-first analysis of OpenAI's Pentagon agreements, evidence behind the Anthropic exclusion narrative, unresolved legal questions, and policy implications.
Coding AI in 2026 Is Better Understood Through Role Division Than Through a Single Ranking
Instead of forcing GPT-5.3-Codex, GPT-5.4, and Claude Opus 4.6 into a single winner ranking, this article compares them through role division across implementation, integrated reasoning, and long-horizon autonomous work.
Can You Trust the "Best AI Coder" Rankings? OpenAI Audited SWE-Bench Pro, Found ~30% of Tasks Broken, and Retracted Its Recommendation
OpenAI audited SWE-Bench Pro, the leading coding benchmark, found that roughly 30% of its public tasks were flawed, and retracted its recommendation. Here is what actually happened, whether the score gaps between GPT, Claude and Gemini are real, why models get "trained to the test," and how to measure practical ability instead.
The Day AI Got Borders: Will Intelligence Be Export-Controlled?
A long-form essay on the suspension of Claude Fable 5 and Claude Mythos 5, model weights, export controls, cyber defense, technological sovereignty, and who should govern dangerous knowledge.
The OpenAI Trial and the Moment a Well-Intentioned Organization Becomes a Giant Company
A governance-focused analysis of the Musk-OpenAI lawsuit, nonprofit ideals, frontier AI capital demands, Anthropic, DeepSeek, Gemini, Copilot, and the institutional contradictions of AI companies.