40% off everything — use code SAVE40 at checkout · ends in …
Skip to content
phpguru.store
Lesson 1 of 12 4 min read Free preview

What an AI API really is (and your first call from PHP)

A language model API is an HTTPS endpoint that takes text and returns text. What that means for latency, cost and reliability, where it belongs in a PHP app, and a first working call to Claude with nothing but cURL.

Strip away the hype

From PHP's point of view, an AI model is one more HTTPS API. You send a JSON request containing some text; a few seconds later you get JSON back containing more text. There is no magic library to install and no model running on your server. Everything else in this course — prompts, structured output, streaming, search, safety — is engineering around that one request.

Three facts about that request shape every design decision:

  • It is slow. A database query takes milliseconds. A model call takes one to thirty seconds, depending on how much it writes. Anything a user waits for needs a loading state, a timeout, and often a background job (lesson 12).
  • It costs money per call. Providers bill by tokens — pieces of words, roughly four characters of English each — counted separately for what you send (input) and what comes back (output). A feature that sends a whole ticket history on every page view gets expensive quietly. Lesson 3 puts a meter on every call.
  • It is not deterministic. The same request can return different wording, and occasionally something wrong or malformed. You validate the output like any other untrusted input (lessons 5 and 11).

Where AI fits — and where it doesn't

Good jobs for a model in a business app are the ones a person would otherwise do by reading and writing text: summarising a long ticket thread, drafting a reply for an agent to edit, pulling the fields out of a pasted invoice, finding documents by meaning rather than exact words, answering "how do I…" from your own manual.

Bad jobs are the ones your code already does perfectly: arithmetic, totals, permissions, anything that must be exactly right every time. A model should never decide whether a user may see a record or what an invoice total is. It proposes; your code and a human decide.

The project

Across the course you will add AI features to one small application: a support desk with customers, tickets, messages and a knowledge-base of help articles. It is the kind of system most PHP developers have built, and every feature transfers directly to hotel, school, clinic or invoicing software. By the end it will summarise tickets, draft replies, extract data from pasted text, stream answers, search the knowledge base by meaning, and answer questions from it with citations.

Get a key

Create an API key with at least one provider: Anthropic (console.anthropic.com), OpenAI (platform.openai.com) or Google (aistudio.google.com). All three sell pay-as-you-go credit; a few dollars covers every exercise in this course. Treat the key like a database password — lesson 3 is about exactly that. For now, put it in an environment variable, not in your code:

export ANTHROPIC_API_KEY="sk-ant-..."

On Windows, set it in System Properties → Environment Variables, or in XAMPP's apache/conf/extra/httpd-xampp.conf with SetEnv. Restart the terminal or Apache afterwards.

Your first call

This script sends one message to Claude through Anthropic's Messages API and prints the answer. It uses only PHP's built-in cURL extension.

<?php
$apiKey = getenv('ANTHROPIC_API_KEY');
if (!$apiKey) {
    exit("Set ANTHROPIC_API_KEY first.\n");
}

$payload = [
    'model' => 'claude-haiku-4-5-20251001',
    'max_tokens' => 300,
    'messages' => [
        ['role' => 'user', 'content' => 'In two sentences: what is PHP-FPM?'],
    ],
];

$ch = curl_init('https://api.anthropic.com/v1/messages');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 60,
    CURLOPT_HTTPHEADER => [
        'content-type: application/json',
        'x-api-key: ' . $apiKey,
        'anthropic-version: 2023-06-01',
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
]);
$raw = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$data = json_decode((string) $raw, true);
if ($status !== 200) {
    exit("HTTP $status: " . ($data['error']['message'] ?? $raw) . "\n");
}

echo $data['content'][0]['text'], "\n";
echo "Tokens: {$data['usage']['input_tokens']} in, {$data['usage']['output_tokens']} out\n";

Run it from the terminal with php first-call.php. Read the request and response carefully, because every provider follows the same shape:

  • model picks which model answers. Providers retire and add models regularly, so model names belong in configuration, never scattered through code. Check the provider's current model list when you start; the name above is a small, fast Claude model.
  • max_tokens is a hard cap on the length of the answer — and therefore on its cost. Always set it.
  • messages is the conversation so far: alternating user and assistant turns. The API remembers nothing between calls; if you want a follow-up question to know about the first answer, you send the whole conversation again.
  • usage in the response tells you exactly how many tokens you paid for. Lesson 3 records it on every call.

When it fails

Change the key to something wrong and run it again: HTTP 401 with an authentication error. Set max_tokens to 0: HTTP 400. Turn off your network: curl_exec returns false. These are the failures you will handle properly in lesson 2 — for now, notice that the script never assumes success before reading the status code.

Try it

  • Ask for the answer in Hindi, then in bullet points. Watch the output tokens change.
  • Set max_tokens to 20 and see how the answer is cut off. Look at stop_reason in the response (max_tokens instead of end_turn).
  • Send a two-turn conversation: your question, an assistant message with the model's earlier answer, then a follow-up question. Remove the middle turn and ask again — the model no longer knows what "it" refers to.
  • If you have an OpenAI or Gemini key instead, don't adapt this script yet: lesson 2 builds one client for all three.

That was lesson 1. The other 11 are one payment away.

Next up: One client, three providers. Buy once, read every lesson online with your progress saved, and keep the whole course as a Word file.

Get the course · ₹1,499$39