Sub topic 1
What an LLM API Call Is: HTTP, JSON and Endpoints
A hosted large language model (LLM) is a program running on someone else's servers. Your code does not load the model. It sends a message over the network and receives text back. This chapter explains that exchange at the protocol level, so every later chapter (authentication, tokens, retries, streaming) has something concrete to attach to.
Prerequisites
This chapter assumes you have:
- Basic programming skill in Python or a similar language.
- Familiarity with JSON objects, arrays, strings and numbers.
- A general idea of what an HTTP request and a status code are.
- Comfort using environment variables and a terminal.
The examples use the widely adopted chat-completions request shape. Field names, URLs and parameters differ between providers, so check your provider's documentation before copying anything.
To run the examples, set two environment variables. OPENAI_API_KEY holds your key and LLM_MODEL holds the name of a model your account can use. Chapter 2 covers keys in detail. For now, treat the key as a password that you never write into source code.
The Core Idea: One Request, One Response
An LLM API call is an ordinary web request. Your program sends an HTTP request containing JSON. The server runs the model and sends back an HTTP response, also containing JSON. Nothing about the transport is specific to AI.
HTTP (Hypertext Transfer Protocol) is the text-based request and response protocol that web clients and servers use. JSON (JavaScript Object Notation) is a text format for structured data. LLM providers choose both because every language has libraries for them.
Anatomy of an HTTP Request
Every request has four parts.
| Part | What it is | Example in an LLM call |
|---|---|---|
| Method | The verb describing the action | `POST` |
| URL | The address of the resource | `https://api.openai.com/v1/chat/completions` |
| Headers | Key-value metadata about the request | `Authorization`, `Content-Type` |
| Body | The payload, here a JSON document | `model` and `messages` fields |
Generation calls almost always use POST, because you send data for the server to process. A GET request has no body by convention, so it suits reading things such as a list of available models.
Endpoints
An endpoint is a specific URL that performs one kind of operation. The URL splits into a base and a path:
- The base, such as
https://api.openai.com, identifies the provider's server. - The path, such as
/v1/chat/completions, identifies the operation. Thev1segment is the API version.
A provider usually exposes several endpoints: one for chat generation, one for text embeddings, one for listing models, and so on. Sending a chat body to the wrong endpoint fails, because each endpoint expects different fields. Many providers and self-hosted servers also copy the chat-completions shape. With those you change only the base URL and key, and the rest of your code stays the same.
Headers
Two headers appear in nearly every call:
Content-Type: application/jsontells the server how to parse the body. If you omit it, many servers reject the request or treat the body as plain text.Authorization: Bearer <key>proves who you are. The word "Bearer" means that whoever holds the token is accepted.
Anatomy of an HTTP Response
A response has a status code, headers and a body.
The status code is a three-digit number. The first digit gives the class:
| Range | Meaning | Typical cause in LLM calls |
|---|---|---|
| 2xx | Success | `200 OK` with generated text |
| 4xx | The request was wrong | Bad JSON, wrong field, missing or bad key |
| 5xx | The server failed | Overload or an internal error at the provider |
Chapter 8 covers individual codes and rate limits in detail. The rule to take away now is that you must check the status code before you read the body. A 4xx or 5xx response still has a JSON body, but its shape is an error description, not generated text. Code that assumes success will crash with a confusing KeyError instead of showing the real problem.
Response headers carry metadata. Some providers report remaining quota or a Retry-After value there. The body of a successful call holds the generated text and a token count. Chapter 4 covers reading those fields.
JSON: The Shared Language
JSON has six value types: object, array, string, number, boolean and null. A chat request body uses most of them:
{
"model": "your-model-name",
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what an API key is in one sentence."}
]
}The top-level object has a string field model and an array field messages. Each element of the array is another object. Chapter 3 explains what each field means. Here the point is only that the body is valid JSON, and the server rejects anything that is not.
Several details cause real errors:
- JSON strings need double quotes. Single quotes are invalid.
- JSON allows no trailing commas and no comments.
- Newlines and quotes inside a string must be escaped (
\n,\"). A JSON library does this for you. Building JSON by pasting strings together is how prompts containing a quotation mark break requests. nullis a value, distinct from a missing key. Some APIs treat the two differently.
In Python, pass a dictionary through a library and let it serialize. Do not format the JSON text yourself.
Your First Call with curl
curl is a command-line tool for sending HTTP requests. It is the quickest way to see the raw exchange, with no library hiding the details.
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d @- <<EOF
{
"model": "$LLM_MODEL",
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what an API key is in one sentence."}
]
}
EOFEach part maps to the anatomy above:
- The URL is the endpoint. With
-d, curl switches the method toPOSTautomatically. - Each
-Hadds one header. -d @-reads the body from standard input, and the heredoc (<<EOF ... EOF) supplies it.- The shell expands
$OPENAI_API_KEYand$LLM_MODELbefore curl runs. The key stays out of the command text you might save in shell history or a script.
To see the status code and response headers, add -i to the curl command. To fail on HTTP errors with a nonzero exit code, add --fail-with-body. This flag needs a recent curl and still prints the error body.
The Same Call in Python
In code, a library builds the request and parses the response. This example uses the requests package, which you can install with pip install requests.
import os
import requests
URL = "https://api.openai.com/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
}
payload = {
"model": os.environ["LLM_MODEL"],
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what a token is in one sentence."},
],
}
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=30)
resp.raise_for_status()
data = resp.json()
choice = data["choices"][0]
print(choice["message"]["content"])
print("finish_reason:", choice["finish_reason"])
print("usage:", data["usage"])Four habits in this short program carry over to production code:
json=payloadserializes the dictionary and sets the JSON content type for you. You still pass the authorization header yourself.timeout=30stops the program from waiting forever.requestshas no default timeout, so a stalled connection would hang your process indefinitely.raise_for_status()raises an exception on 4xx and 5xx codes, so you never parse an error body as if it were an answer.os.environ[...]raisesKeyErrorif the variable is missing. That fails early and loudly instead of sending a request with an empty key.
You do not need to understand every field the code prints yet. The next chapters explain finish_reason and usage.
A Stateless Protocol
HTTP is stateless. The server keeps no memory of your previous request when it handles the next one. An LLM API inherits this. The model does not remember what you asked a minute ago unless the new request contains that history. Chapter 7 shows how to manage this. Keep it in mind now, because it explains why every request carries a complete messages array.
Where Calls Fail
Most first-day failures happen before the model is involved. They show up as specific symptoms:
| Symptom | Likely cause |
|---|---|
| `401` status | Missing, wrong or expired key, or a malformed `Authorization` header |
| `404` status | Wrong path, a typo in the URL, or a model name your account cannot access |
| `400` status | Invalid JSON, a missing required field or a wrong field type |
| `KeyError` in your code | You parsed an error response as if it were a success |
| Program hangs | No timeout was set |
| Connection error | No network, a proxy blocking the call or a wrong host name |
When a call fails, print the status code and the response body first. Providers usually put a readable message in the error body, such as which field is invalid.
Provider Differences
The chat-completions shape is a common convention, not a standard. Other providers use different paths, put the key in a different header, name the message list differently or return text in a different place. When you read a new provider's documentation, check these items first: base URL and path, authentication header, required body fields, and the location of the generated text in the response. The structure of this chapter (method, URL, headers, body, status, response body) applies to all of them.
Exercise
You send a chat request with curl and get a 400 status. Your Python version of the same request, built with json=payload, works. The curl body was assembled with a shell string that contains a user question with a double quote in it. What is the most likely cause, and what is the fix?
Show answer
The unescaped double quote ended the JSON string early, so the body was invalid JSON and the server rejected it with 400. The fix is to escape the quote as \", or better, to build the body with a JSON library such as json=payload in Python, which escapes strings automatically.
Exercise
Why must you check the HTTP status code before reading data["choices"][0], and which requests call does this for you?
Show answer
A 4xx or 5xx response has a JSON body shaped like an error, with no choices array, so reading it as a success raises a confusing KeyError and hides the real message. resp.raise_for_status() raises an exception for error status codes, so the code never reaches the parsing step.