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
requestsand read its JSON response. - Send the token in the
Authorizationheader, 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
- The lesson Turning a Python project into a tool (in French),
which sets the
certcheckcontract: exit codes 0, 1 and 2. This lesson adds code 3, "publishing failed". - Reading short Python; the syntax is covered by the Python fundamentals path (in French).
- Knowing what JSON is: objects between braces, lists between brackets (see JSON in Python (in French)).
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.1Host: forge.entreprise.localAuthorization: token <jeton>Accept: application/json
HTTP/1.1 200 OKContent-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 logsrequests.get(f"{BASE}?access_token={jeton}", timeout=5)
# correct: the token stays in the headerrequests.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.
The table gives the meaning of the codes you will meet most often with a forge, and what each error asks you to fix.
| Code | Meaning | What to fix |
|---|---|---|
401 | token missing, expired or refused | the token |
403 | valid token but insufficient permission | the token's permissions |
404 | repository or resource not found | the URL |
503 | server unavailable | nothing 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):
2xxsucceeded,4xxfaulty request,5xxfailing 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.
requestscalls the API in one statement;reponse.json()decodes the received JSON.- The token travels in the
Authorizationheader, 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 a4xxor5xxinto an exception; a singleexcept requests.RequestExceptionalso catches the timeout and a dropped network.- An API outage has its own exit code (3), distinct from the business alert (1).
POSTis 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.
Always in the header
A token pasted in the URL (?access_token=...) is written everywhere: server and proxy logs, shell history, your own tool's error message. A leaked token must be revoked.requests.get(url, headers={"Authorization": f"token {jeton}"}, timeout=5)
- Forgejo accepts
Authorization: token <token>andAuthorization: Bearer <token>. - Read the token from an environment variable, not from a command-line option, which
psshows to every user of the machine. - Give it the minimum scope: a token limited to issues limits the damage if it leaks.
Without a timeout, the tool waits forever
requests sets no timeout by default. A tool launched by cron stays hung, and the next night a second copy starts.reponse = requests.get(url, headers=entetes, timeout=5)
- Against a silent server,
timeout=1raises aReadTimeoutexception after one second. - It inherits from
requests.RequestException, like everyrequestserror: a singleexceptcatches it. - Set the timeout on every call, it cannot be configured once and for all.
The status code decides
| Code | Meaning | What to fix |
|---|---|---|
2xx |
succeeded | nothing |
401 |
token missing, expired or refused | the token |
403 |
valid token, insufficient permission | the token's permissions |
404 |
resource or repository not found | the URL |
5xx |
the server failed | nothing on your side, retry after a delay |
reponse.raise_for_status()
donnees = reponse.json()
A 401 is not fixed by retrying: you have to change the token.Search, compare, then create
GET changes nothing on the server and can be repeated safely; POST creates on every call. For a rerun to leave the same state:- list the open issues;
- compare the exact title, which acts as the key and must stay constant (no date in it);
- create only if no issue carries it.
An outage is not a finding
In thecertcheck contract, 1 means "at least one certificate to renew" and 3 means "publishing failed". An uncaught exception makes Python exit with code 1: a network outage would pass for a security alert.try:
tickets = lister_tickets(jeton)
except requests.RequestException as exc:
print(f"certcheck: forge injoignable : {exc}", file=sys.stderr)
sys.exit(3)
- The message goes to standard error, so the certificate results stay readable on standard output.
- Never print the token or the header, even in
--verbosemode.
Two topics to explore further
- Retry: some errors (
429,503) go away on their own. You retry a few times, waiting longer and longer between attempts. - Pagination: an API list is split into pages. A Forgejo instance returns 30 items by default and 50 at most, adjustable values that the instance publishes at
/api/v1/settings/api; the list is read with thepageandlimitparameters.