Call a Web API by Hand
Many useful programs do not run on your own computer. A weather service, a translation service or a language model runs on a computer somewhere else, and your Python program can ask it for an answer by sending it a message over the internet. This page explains what such a message looks like, what comes back, how to tell whether it worked, and how to pick the one value you need out of the reply.
A program that answers other programs
A website is made for people: you read it and click on it. A web API is made for programs instead. It is a program running on another computer, usually called a server, that waits for messages from other programs and answers each one. API stands for Application Programming Interface, which simply means "the way a program lets other programs use it".
To reach a web API, your program needs its address. That address is a URL (Uniform Resource Locator), the same kind of address you type into a browser. A URL names the computer to talk to and, after it, the path of the one service you want on that computer.
- a web API at https://api.example.com
- your computer
- request
- response
| Part | In the example | What it says |
|---|---|---|
| scheme | https:// | how to talk: HTTP, encrypted |
| host | api.example.com | which computer to talk to |
| path | /v1/chat/completions | which service on that computer |
The address https://api.example.com is made up for this page. A real service lists its own URLs in its documentation, and a server running on your own computer has an address that starts with http://localhost or http://127.0.0.1, the name and the number every computer uses for itself.
One request, one response
Programs and web APIs talk in a fixed format called HTTP. The conversation always has two halves. Your program sends a request, and the server sends back exactly one response. Nothing happens on the server until a request arrives.
A request is made of four parts:
- the method, a word that says what you want done:
GETto fetch something,POSTto send data for the server to work on; - the URL, the address of the service;
- the headers, short lines of extra information, each a name, a colon and a value, such as
Content-Type: application/json; - the body, the data itself. A
GETrequest usually has none; aPOSTrequest carries one.
Here is a whole request written out as text, the way it travels. The headers come first, then one empty line, then the body:
POST /v1/chat/completions HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer my-secret-key
{"model": "some-model", "messages": [{"role": "user", "content": "Hello"}]}The response has a similar shape. Its first line holds a status code, a three-digit number that says whether the request worked and, if not, why. Headers follow, and then a body with the answer, or with a description of what went wrong.
HTTP/1.1 200 OK
Content-Type: application/json
{"answer": "Hello to you too"}Status codes: did it work?
The status code is the first thing to read in a response, because the body only means what you expect when the request succeeded. The first digit tells you the group: codes from 200 to 299 mean success, codes from 400 to 499 mean the request itself had a problem, and codes from 500 to 599 mean the server failed while handling it.
Three codes come up again and again when you call an API:
| Code | Name | What happened |
|---|---|---|
| 200 | OK | The request succeeded; the body holds the answer. |
| 401 | Unauthorized | The key was missing or wrong, so the server does not know who is calling. |
| 404 | Not Found | Nothing exists at that address, often because of a typo in the URL. |
The name "Unauthorized" is a little misleading. A 401 does not mean "you are not allowed"; it means the server could not check who you are, which in practice almost always means a wrong or missing key. A separate code, 403 Forbidden, is for a caller the server recognises but does not permit.
A status code needs a server that answers. When the server is not running at all, or the address points at no computer, there is no response and therefore no status code. Python reports that as an error of its own, a connection error, which you will meet below.
True or false?
A response with status code 404 means the server is switched off.
False. A 404 is an answer, so the server is running. It says that nothing exists at the path you asked for. A server that is switched off sends no response at all.
Sending a wrong API key usually gets the status code 401.
True. A 401 means the request lacked valid credentials, and a wrong or missing key is exactly that.
Any status code from 200 to 299 counts as a success.
True. The first digit gives the group, and 2 is the success group. 200 OK is the most common one.
Sending a request from Python
Python can send HTTP requests with its standard library, but most programs use requests, a third-party package made for exactly this job. Like any package, it is added to a project first, for example with uv add requests. Then a request is one function call, named after the method:
import requests
response = requests.get("https://api.example.com/v1/cards/7", timeout=10)
if response.status_code == 200:
print("It worked")
print(response.text)
else:
print("The request failed with status", response.status_code)requests.get sends the request and waits until the response has arrived. It gives back a response object: response.status_code holds the status code as a whole number, and response.text holds the body as a string.
The argument timeout=10 says how many seconds to wait for the server before giving up. Without it, requests waits forever, so a server that never answers would freeze the program. Its documentation advises a timeout on nearly every request.
Two things surprise people at first. The first is that a 401 or a 404 is not a Python error. The server did answer, so requests hands you the response normally, and it is your code that has to look at the status code, as the if above does.
The second is that a missing server is an error. There is no response to hand back, so requests raises requests.exceptions.ConnectionError, and the program stops with a traceback unless a try and except handles it.
True or false?
When the server answers 401, requests.get raises an exception and the program stops.
False. The server did answer, so requests returns the response normally with status_code set to 401. Your code decides what to do with it.
Without a timeout, a call to requests.get can wait forever for a server that never answers.
True. requests has no timeout of its own unless you pass one, so it keeps waiting.
JSON in the request and in the response
A body is only text, so both sides need to agree on how that text is laid out. Most web APIs use JSON, the text format for data in which curly brackets hold named entries (a dictionary in Python) and square brackets hold lists.
Sending data uses the method POST, so the call is requests.post. You build the data as a normal Python dictionary and pass it with the json argument. requests then does three things for you: it turns the dictionary into JSON text, puts that text in the body, and adds the header Content-Type: application/json so the server knows how to read it:
import requests
payload = {"question": "Capital of France?", "level": 2}
response = requests.post("https://api.example.com/v1/check", json=payload, timeout=10)
data = response.json()
print(data["result"]["score"])On the way back, response.json() does the opposite: it reads the JSON text of the body and gives you Python data, usually a dictionary. The values inside can themselves be dictionaries and lists, nested as deep as the API likes. Suppose the body of the response above is this:
{
"result": {
"score": 1.0,
"tags": ["geography", "europe"]
}
}To reach one value, you take one step at a time, each step with the square brackets you already know: a key for a dictionary, a position for a list. data["result"] is the inner dictionary, data["result"]["score"] is 1.0, and data["result"]["tags"][0] is the string "geography". Reading the brackets from left to right follows the path from the outside in.
An error response can carry a JSON body too, describing what went wrong. So response.json() working tells you nothing about success; only the status code does. Check it before you look for the value you need, or a missing key will raise a KeyError that hides the real reason.
True or false?
If response.json() gives back a dictionary without an error, the request succeeded.
False. Servers often send JSON with error details along with a 401 or a 500. Only the status code says whether the request worked.
With the json argument, requests adds the Content-Type header for you.
True. It encodes the dictionary as JSON and sets Content-Type: application/json, unless you set that header yourself.
Saying who is calling: the API key
Many APIs answer only callers they know, because each answer costs the provider something, or because the data belongs to someone. When you sign up, the provider gives you an API key: a long secret string that identifies you. Every request carries it, so the server can tell who sent it and refuse everyone else with a 401.
The key travels in a header, not in the body or the URL. Most language model APIs expect the header named Authorization, with the word Bearer, one space, and then the key. In requests you pass headers as a dictionary of strings:
import os
import requests
api_key = os.environ["API_KEY"]
headers = {"Authorization": f"Bearer {api_key}"}
response = requests.get("https://api.example.com/v1/me", headers=headers, timeout=10)
print(response.status_code)The key is read from an environment variable, never typed into the code, because anyone who sees the key can make requests in your name. If the key is wrong, expired or has a typo, the server answers 401, which is the clue to check the key before anything else. Header names do not care about capital letters (authorization works too), but the value has to be exact.
True or false?
An API key is usually sent as one of the entries in the JSON body.
False. It goes in a header. For OpenAI-style APIs that is Authorization: Bearer followed by the key.
A chat completion request
Everything so far comes together in the request that asks a language model for an answer. OpenAI first published the format of this request under the name Chat Completions. Many other providers accept the same format, and so do programs that run a model on your own computer, such as Ollama, LM Studio or vLLM. Because they share it, the same code can talk to any of them by changing only the URL, the key and the model name.
The request is a POST to a URL ending in /v1/chat/completions, with the key in the Authorization header. Its JSON body needs two entries:
model, the name of the model that should answer, as the provider writes it;messages, a list of the conversation so far, where each message is a dictionary with arole(who is speaking, such as"user") and itscontent(the text).
import os
import requests
url = "https://api.example.com/v1/chat/completions"
headers = {"Authorization": f"Bearer {os.environ['API_KEY']}"}
body = {
"model": os.environ["MODEL"],
"messages": [
{"role": "user", "content": "What is the capital of France?"},
],
}
response = requests.post(url, headers=headers, json=body, timeout=30)
if response.status_code == 200:
data = response.json()
print(data["choices"][0]["message"]["content"])
else:
print("The model could not answer, status", response.status_code)The answer is not at the top of the response. The body is a dictionary, and inside it is a list called choices. It is a list because the format allows asking for several alternative answers at once. Each choice holds a message with the role "assistant", and the content of that message is the text the model wrote. Beside the choices sits usage, which counts the pieces of text, called tokens, that went in and came out. A shortened response looks like this (the text of a real answer differs from one call to the next):
{
"object": "chat.completion",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "The capital of France is Paris."
},
"finish_reason": "stop"
}
],
"usage": {"prompt_tokens": 14, "completion_tokens": 8, "total_tokens": 22}
}- data dictionary
- ["choices"] list
- [0] dictionary
- ["message"] dictionary
- ["content"] string
- data to ["choices"]
- ["choices"] to [0]
- [0] to ["message"]
- ["message"] to ["content"]
Each step of data["choices"][0]["message"]["content"] opens one layer: a key into the outer dictionary, a position into the list, a key into the choice, and a key into the message. When a step fails with a KeyError, print the whole data and follow the brackets by eye; most often the status code was not 200 and the body describes an error instead of holding choices.
True or false?
The answer text of a chat completion is at data["message"].
False. There is no top-level message. The answer sits inside the choices list, at data["choices"][0]["message"]["content"].
The same chat completion request can be sent to a model running on your own computer, if its server speaks this format.
True. Local servers such as Ollama, LM Studio and vLLM accept requests at /v1/chat/completions; only the URL, the key and the model name change.