Tutorials

ChatGPT and Claude API Integration Guide

C
Codeison Team
Apr 11, 2026 4 min read 700 views

Quick Answer

A practical guide to integrating ChatGPT and Claude APIs into your applications. Covers setup, code examples, model selection, function calling, RAG patterns, and cost management.

Getting Started with ChatGPT and Claude APIs

Large Language Model (LLM) APIs from OpenAI and Anthropic allow you to integrate advanced AI capabilities into any application. Whether you are building a chatbot, automating content creation, analyzing documents, or building a coding assistant, these APIs provide the intelligence layer that powers modern AI applications.

OpenAI ChatGPT API

Setup

  1. Create an account at platform.openai.com.
  2. Generate an API key in the API Keys section of your dashboard.
  3. Install the official SDK for your language:
    • Python: pip install openai
    • Node.js: npm install openai
    • PHP: composer require openai-php/client
  4. Set your API key as an environment variable: OPENAI_API_KEY=your_key_here

Basic API Call (Python)

from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful e-commerce assistant."},
        {"role": "user", "content": "Write a product description for a wireless Bluetooth speaker."}
    ],
    max_tokens=500,
    temperature=0.7
)

print(response.choices[0].message.content)

Function Calling

Function calling allows the AI to invoke your application's functions to retrieve real-time data or perform actions. Define functions with JSON schemas, and the model will call them when appropriate during a conversation. This is essential for building AI agents that can look up orders, check inventory, or update records.

Anthropic Claude API

Setup

  1. Create an account at console.anthropic.com.
  2. Generate an API key.
  3. Install the SDK:
    • Python: pip install anthropic
    • Node.js: npm install @anthropic-ai/sdk
  4. Set your API key: ANTHROPIC_API_KEY=your_key_here

Basic API Call (Python)

import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=500,
    messages=[
        {"role": "user", "content": "Write a product description for a wireless Bluetooth speaker."}
    ],
    system="You are a helpful e-commerce assistant."
)

print(message.content[0].text)

Tool Use

Claude's tool use feature works similarly to OpenAI's function calling. Define tools with input schemas, and Claude will generate tool calls when it needs external data. Your application executes the tool and sends the result back to Claude for the final response.

Key API Concepts

Models

ProviderModelBest ForApproximate Cost
OpenAIGPT-4oComplex reasoning, code$2.50/$10 per M tokens
OpenAIGPT-4o-miniSimpler tasks, high volume$0.15/$0.60 per M tokens
AnthropicClaude SonnetBalanced quality and speed$3/$15 per M tokens
AnthropicClaude HaikuFast, cost-effective$0.25/$1.25 per M tokens

Temperature

Temperature controls response randomness. Lower values (0.0-0.3) produce consistent, deterministic outputs ideal for data extraction and classification. Higher values (0.7-1.0) produce more creative, varied responses suitable for content generation. For most application use cases, a temperature of 0.3-0.5 works well.

Token Management

Tokens are the unit of measurement for API usage and billing. Roughly, 1 token equals 4 characters in English. Track token usage to manage costs and stay within rate limits. Use the max_tokens parameter to cap response length and prevent runaway costs.

Common Integration Patterns

Content Generation Pipeline

Automate product descriptions, marketing copy, email templates, and blog content. Use system prompts to maintain brand voice consistency across all generated content. Process items in batches and cache results to minimize API calls.

Retrieval-Augmented Generation (RAG)

Combine your own data with AI intelligence. Store your product catalog, documentation, or knowledge base as embeddings in a vector database. When a user asks a question, retrieve relevant documents and include them in the API call context. This grounds the AI's responses in your actual data, dramatically reducing hallucination.

Structured Data Extraction

Extract structured data from unstructured text. Parse customer emails to extract order numbers, product names, and issue types. Analyze reviews to extract sentiment and key themes. Convert natural language queries into database queries.

Best Practices

  • Never expose API keys in client-side code. All API calls should go through your backend server.
  • Implement request rate limiting to prevent accidental cost spikes.
  • Cache responses for identical or similar queries to reduce API costs.
  • Use the cheapest model that meets your quality requirements. Start with mini/haiku and upgrade only if needed.
  • Log all API requests and responses for debugging and cost monitoring.
  • Implement proper error handling for rate limits (429), timeouts, and API errors.
  • Set spending limits in your API dashboard to prevent unexpected charges.

Frequently Asked Questions

Which is better for my application, ChatGPT or Claude?
Both are excellent. ChatGPT excels at code generation and has broader tool ecosystem support. Claude tends to be more accurate, handles longer contexts better, and has stronger safety guardrails. For customer-facing applications, Claude is often preferred. For developer tools and code generation, ChatGPT is popular.
How much does it cost to use the ChatGPT API?
Costs are based on token usage. GPT-4o costs about $2.50 per million input tokens and $10 per million output tokens. GPT-4o-mini is much cheaper at $0.15/$0.60. A typical chatbot handling 1,000 daily conversations costs $30-200 per month depending on conversation length and model choice.
Can I use these APIs with PHP?
Yes, both APIs can be called from PHP. OpenAI has a community PHP client (openai-php/client via Composer). For Claude, you can use the HTTP API directly with PHP curl or Guzzle. The APIs are standard REST endpoints that work with any HTTP-capable language.
How do I prevent the AI from making up information?
Use Retrieval-Augmented Generation (RAG): provide the AI with your actual data in the conversation context and instruct it to only answer based on the provided information. Set temperature to 0-0.3 for factual applications and validate critical outputs before acting on them.
Is it safe to send customer data to AI APIs?
Both OpenAI and Anthropic have data processing agreements and do not use API data for training by default. However, anonymize sensitive data when possible, comply with your privacy policy, and review each provider data handling policies. For highly sensitive data, consider on-premise AI solutions.

Need Custom AI Integration?

We build production-ready AI applications using ChatGPT and Claude APIs, tailored to your business requirements.

Get Expert Tips in Your Inbox

Join 1,000+ developers who get our weekly insights on e-commerce development.

No spam. Unsubscribe anytime.

Trusted by businesses worldwide

80+
Products
1426+
Reviews
58+
Services
8+
Years Experience