Creation: 2020-07-07

Comment lire une API au format JSON

Le principe est de lire des informations hébergées sur un serveur qui propose une API pour les exploiter.

Exemple de site

Lecture avec curl

$ curl 'https://api.exchangeratesapi.io/history?start_at=2020-07-01&end_at=2020-07-05&symbols=USD,CAD'
{"rates":{"2020-07-02":{"CAD":1.5343,"USD":1.1286},"2020-07-01":{"CAD":1.5217,"USD":1.12},"2020-07-03":{"CAD":1.5233,"USD":1.1224}},"start_at":"2020-07-01","base":"EUR","end_at":"2020-07-05"}

Le même exemple avec le formatage de jq:

$ curl 'https://api.exchangeratesapi.io/history?start_at=2020-07-01&end_at=2020-07-05&symbols=USD,CAD' | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   191  100   191    0     0    135      0  0:00:01  0:00:01 --:--:--   135
{
  "rates": {
    "2020-07-02": {
      "CAD": 1.5343,
      "USD": 1.1286
    },
    "2020-07-01": {
      "CAD": 1.5217,
      "USD": 1.12
    },
    "2020-07-03": {
      "CAD": 1.5233,
      "USD": 1.1224
    }
  },
  "start_at": "2020-07-01",
  "base": "EUR",
  "end_at": "2020-07-05"
}

Lecture avec Python

Ici on récupère l'historique du cours des devises souhaitées comprise entre 2 dates:

api.py
import requests
from datetime import date, timedelta
 
end_date = date.today()
start_date = end_date - timedelta(days=30)
currencies = ["USD", "CAD"]
 
r = requests.get(f"https://api.exchangerratesapi.io/history?"
                 f"start_at={start_date}&"
                 f"end_at={end_date}&"
                 f"symbols={','.join(currencies)}")

Outils API REST

Exemple de données JSON

Tableau

{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}