Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Call a REST API with Python and requests

16 min read
Improve this page

Calling a REST API from a tool means sending an HTTP request and reading a response, with three precautions that a hand-typed curl makes you forget: the token in a header, a timeout, and an error turned into a clear message. This lesson is for an Ops engineer who is new to development. It uses requests, the most widely used Python library for this job, on a real case: certcheck, a Python tool that checks the expiry date of certificates and, with --publish, opens a ticket on the Forgejo forge (a self-hosted Git forge) when one of them needs renewing. The identifiers in the code (jeton, reponse, lister_tickets) are in French, like the lab's code.

What you will learn

  • Read an HTTP request and response: method, URL, headers, body, code.
  • Name the REST principles: client-server, stateless, cache, uniform interface, layers.
  • Call an API with requests and read its JSON response.
  • Send the token in the Authorization header, never in the URL.
  • Set a timeout and turn an HTTP error into an exit code.
  • Search before creating so you do not duplicate a ticket.

Prerequisites

What is a REST API for a tool?

A REST API is a web service that a program calls over HTTP. It exposes resources (a ticket, a server), each at a URL, and the client acts on them with a method: GET to read, POST to create. Data usually travels as JSON. A request and a response each break down into four parts: the start line, the headers (metadata), an empty line, then an optional body. Here, shortened, is the list of open tickets of a Forgejo repository:

GET /api/v1/repos/exploitation/certificats/issues?state=open HTTP/1.1
Host: forge.entreprise.local
Authorization: token <jeton>
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
[{"number": 12, "title": "certcheck : certificats à renouveler", ...}]

The first line of the response carries the status code, three digits whose first one decides what happens next: 2xx the request succeeded, 4xx it is faulty (token refused, unknown URL), 5xx the server failed. The protocol is detailed in HTTP and HTTPS (in French).

This lesson takes the point of view of the tool that calls the API. Writing an API yourself is server-side work: see FastAPI.

What are the principles of REST?

REST is an architectural style, defined by Roy Fielding in his 2000 thesis, and not a protocol or a standard. It sets no message format: it lays down constraints that a web service must follow to stay simple to evolve and to scale out. Fielding describes them in chapter 5 of his thesis. Almost all of them show up in the forge call seen above.

Client-server. The client (certcheck) and the server (the forge) are two separate programs that only know each other through the HTTP interface. The forge can change its database without the tool moving, and the tool can become a script or a web page without the forge knowing.

Stateless. Each request carries everything the server needs to process it: the server keeps no session state between two calls. That is why certcheck sends the token in Authorization on every call, instead of "logging in" once. In practice, any copy of the server that reaches the same data can answer, so you can run several behind a load balancer and replace one without losing a session. The notion is detailed in Reading an architecture (in French) and in Loose coupling and stateless design (in French).

Cache. The server declares whether a response can be reused, and for how long, with the Cache-Control header (HTTP caching is described by RFC 9111). An ETag header identifies a version of the resource: the client sends it back in If-None-Match, and the server answers 304 with no body if nothing has changed. This avoids downloading an unchanged long list of tickets again. The response to a GET can be cached; the response to a POST that creates a ticket cannot, except in special cases.

Uniform interface. All resources are handled the same way. Each one is identified by a URL (the tickets of a repository, one specific ticket), you read or change it through a representation (the JSON exchanged), and the action is expressed by the HTTP method: GET to read, POST to create. A tool that knows how to call an API of this style knows how to call another without learning everything again. Fielding adds two rules: each message describes itself (the Content-Type header gives the format of the body), and the response contains links to the next actions.

Layered system. Between the client and the final server there may be a proxy, a load balancer or an API gateway. The client sees a single address and does not know how many machines answer behind it. These intermediaries can filter, cache or spread the load.

Code on demand. The only optional constraint: the server can send code that the client runs, for example JavaScript in a browser. A tool like certcheck receives none.

Many so-called REST APIs do not apply all these constraints. Most follow client-server, statelessness and the HTTP methods, and ignore the rest, notably the links that the response should provide to guide the client to the next step. For an Ops engineer, what matters is knowing what a constraint promises: statelessness lets you multiply servers, caching avoids pointless calls.

How do you call an API with requests?

A requests call fits in four lines: the method, the URL, the header, the timeout. requests is not in the Python standard library: you declare it like any other dependency (see Python dependencies (in French)). The following function reads the open tickets of a forge. It uses params= to build the ?state=open&type=issues part of the URL, and reponse.json() to decode the received JSON into a list of Python dictionaries. The address 127.0.0.1:8099 is that of the lab's fake forge, a demonstration forge started locally.

import requests
BASE = "http://127.0.0.1:8099/api/v1/repos/exploitation/certificats/issues"
def lister_tickets(jeton):
reponse = requests.get(
BASE,
params={"state": "open", "type": "issues"},
headers={"Authorization": f"token {jeton}"},
timeout=5,
)
reponse.raise_for_status()
return reponse.json()

Against a forge that answers correctly, lister_tickets("jeton-de-demo") returns [] when no ticket is open. Creating a ticket with a POST works the same way:

requests.post(
BASE,
json={"title": "certcheck : certificats à renouveler", "body": "web-02 : expiré"},
headers={"Authorization": f"token {jeton}"},
timeout=5,
)

The json= parameter encodes the dictionary as JSON and adds the Content-Type header. The forge answers 201 (created) with the ticket as JSON, which reponse.json() decodes as above.

requests.get and requests.post are two shortcuts for the same generic form, requests.request(method, url, ...), where the HTTP method is the first argument ("GET", "POST", "PATCH"...). It accepts the same parameters (params=, json=, headers=, timeout=) and serves for the methods that have no shortcut written in this lesson.

Where should the access token go?

The token travels in the Authorization header, never in the URL. A token is an application password: it proves your identity to the API. A URL is written everywhere: in the logs of the server and of the network intermediaries, in the shell history, in the error message of your own tool. A token passed in the URL must then be revoked. The first block is to be avoided, the second is correct:

# ❌ the token ends up in the URL, so in the logs
requests.get(f"{BASE}?access_token={jeton}", timeout=5)
# correct: the token stays in the header
requests.get(BASE, headers={"Authorization": f"token {jeton}"}, timeout=5)

Forgejo accepts the Authorization: token <token> header. The token itself comes from an environment variable (FORGE_TOKEN in certcheck), not from a command-line option, which the ps command shows to every user of the machine. Give it the minimum scope: a token that can only manage tickets limits the damage if it leaks.

Why set a timeout?

Without a timeout, requests waits forever for a response that never comes. A forge that accepts the connection and then goes silent, a firewall that drops packets: the tool launched every night by cron (the Linux task scheduler) stays hung, and the next night a second copy starts. The timeout= parameter sets a limit in seconds. Against a silent server, timeout=1 raises a ReadTimeout exception after one second, whose message looks like:

HTTPConnectionPool(host='127.0.0.1', port=57809): Read timed out. (read timeout=1)

Always set timeout= on every call: requests sets none by default. A 5-second timeout is a reasonable starting point for an internal API. A forge that never answers then produces a clear error within a few seconds, which the tool can turn into a message and an exit code.

What should you do when the API returns an error?

An HTTP error raises nothing by itself: raise_for_status() is what turns it into an exception. Without that call, a 401 response would be treated as a normal response and reponse.json() would decode the error message as if it were data. With it, any 4xx or 5xx code raises an HTTPError. An exceeded timeout and a dropped network raise other exceptions, but all of them inherit from requests.RequestException: a single except is enough to catch them.

The diagram follows a call from top to bottom. Look at the two error exits: the exceeded timeout and the 4xx or 5xx code end up in the same catch, which produces a message on standard error and a precise exit code. Only a 2xx code leads to reading the data.

A requests.get call with a header and a 5-second timeout. If no response arrives within 5 seconds, a timeout or network exception is raised. Otherwise raise_for_status examines the HTTP code: a 2xx code leads to reponse.json, which reads the data, and a 4xx or 5xx code raises an HTTPError exception. Both exceptions end up in a single except requests.RequestException, which writes a message to standard error and then exits with code 3.noyes2xx4xx or 5xxrequests.get(url, headers=..., timeout=5)Response receivedwithin 5 seconds?Exception:timeout or network downreponse.raise_for_status()HTTP codereponse.json()read the dataHTTPError exception(4xx or 5xx)except requests.RequestExceptionMessage on the error outputthen exit code 3callcheckerrorcode statementsuccessnext step
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

The table gives the meaning of the codes you will meet most often with a forge, and what each error asks you to fix.

CodeMeaningWhat to fix
401token missing, expired or refusedthe token
403valid token but insufficient permissionthe token's permissions
404repository or resource not foundthe URL
503server unavailablenothing on your side: retry after a delay

Why a separate exit code? In the certcheck contract, 1 means "a certificate needs renewing" and 2 "unusable call or input". A forge outage that also exited with 1 would send you looking for an alert that does not exist: publishing therefore adds a fourth code to the contract, 3. Here is the sequence, with the lister_tickets function seen above:

try:
tickets = lister_tickets(jeton)
except requests.RequestException as exc:
print(f"certcheck: forge injoignable : {exc}", file=sys.stderr)
sys.exit(3)

With a wrong token, the lab's demonstration forge answers 401 and the message that appears contains 401 Client Error: Unauthorized for url: followed by the address called. That address contains no token, a direct consequence of the rule about the header.

How do you open a ticket without creating a duplicate?

A tool launched by cron must search before creating, otherwise it opens one ticket per night. GET changes nothing on the server, so you can repeat it at will. POST creates on every call: rerun, it creates a duplicate. An action is idempotent when repeating it leaves the same final state; so it is up to the tool to make its publishing idempotent.

To publish without duplicates, the tool lists the open tickets, compares their title to the one it wants to create, and sends the POST only if none carries it. The title acts as the key, so it must stay constant: certcheck : certificats à renouveler, with no date in it. This lesson sticks to the first page of the list, like the lab; the next section points to the pages that cover the rest.

What about retries, pagination and building an API?

Several topics go beyond this introduction and have their own page. An API that sometimes answers 429 or 503 is retried automatically, and a list of more than 30 items arrives split into pages: the guide Call a REST API in Python with requests (in French) covers both. Retrying without side effects is developed in Cloud idempotence (in French). To expose an API rather than call it, see FastAPI. The same subject on the command line is in Consume a REST API with curl and jq.

Put it into practice

In the lab, certcheck already knows how to decide which certificates need renewing; it lacks the two functions that talk to the forge. You write requete() and ticket_existe() in src/certcheck/forge.py with requests, then you try the tool against a fake forge started locally, which answers like the Forgejo API (the --panne option simulates a 503). The validation checks that the token travels in a header and never in the URL, that a silent forge gives code 3 in under 30 seconds, that the 401 and 503 errors give code 3 with a message that cites the HTTP code, that a single ticket is opened with the right title, and that a rerun does not open a second one.

Key takeaways

  • A REST API reads as a request (method, URL, headers, body) and a response (status code, headers, body): 2xx succeeded, 4xx faulty request, 5xx failing server.
  • REST is an architectural style (Fielding, 2000), not a protocol: client-server, stateless (the token goes with every request), cache, uniform interface, layers. Many APIs apply only part of it.
  • requests calls the API in one statement; reponse.json() decodes the received JSON.
  • The token travels in the Authorization header, never in the URL, and comes from an environment variable.
  • Every call carries a timeout=: without it, a silent forge blocks the tool.
  • raise_for_status() turns a 4xx or 5xx into an exception; a single except requests.RequestException also catches the timeout and a dropped network.
  • An API outage has its own exit code (3), distinct from the business alert (1).
  • POST is not idempotent: a tool that is rerun searches before creating, with a constant title as the key.

FAQ: frequently asked questions

The questions below come up when an Ops engineer moves from a curl call to a Python tool that calls an API every night: where to put the token, what timeout to set, how to tell whether the call succeeded and how not to create the same thing twice.