Vai al contenuto principale

Guida rapida Python

Questa guida ti accompagna nell'autenticazione all'API VaultPAM e nel fare la tua prima richiesta utilizzando Python.

Prerequisiti:

  • Python 3.8 o successivo
  • Libreria requests: pip install requests
  • Un account VaultPAM con accesso API abilitato

Passaggio 1 — Installare la libreria requests

pip install requests

Passaggio 2 — Autenticazione

import getpass
import os
import requests

BASE_URL = os.environ.get("VAULTPAM_BASE_URL", "https://api.vaultpam.com")

email = input("Email: ")
password = getpass.getpass("Password: ") # Never commit credentials to source control

response = requests.post(
f"{BASE_URL}/api/v1/auth/login",
json={"email": email, "password": password},
)
response.raise_for_status()

auth_data = response.json()
# Never commit — see auth-flow.md#token-storage
token = auth_data["access_token"]
expires_in = auth_data["expires_in"]
print(f"Authenticated. Token expires in {expires_in} seconds.")
Non committare mai i token

Archivia token in un gestore di segreti o in una variabile di ambiente — non codificare mai le credenziali. Vedi Token Storage.


Passaggio 3 — Ottenere l'organizzazione attiva

org_response = requests.get(
f"{BASE_URL}/api/v1/org/memberships",
headers={"Authorization": f"Bearer {token}"},
)
org_response.raise_for_status()

org_data = org_response.json()
org_id = org_data["active_org_id"]
print(f"Active org: {org_id}")

Passaggio 4 — Elencare i tuoi Safes

safes_response = requests.get(
f"{BASE_URL}/api/v1/safes",
headers={
"Authorization": f"Bearer {token}",
"X-Active-Org-Id": org_id,
},
)
safes_response.raise_for_status()

safes = safes_response.json()
print(f"Found {len(safes)} safe(s):")
for safe in safes:
print(f" - {safe.get('name', safe.get('id'))}")

Esempio completo

import getpass
import os
import sys
import requests

BASE_URL = os.environ.get("VAULTPAM_BASE_URL", "https://api.vaultpam.com")


def get_session(base_url: str) -> tuple[str, str]:
"""Authenticate and return (token, org_id)."""
email = input("Email: ")
password = getpass.getpass("Password: ") # Never commit — see auth-flow.md#token-storage

resp = requests.post(f"{base_url}/api/v1/auth/login", json={"email": email, "password": password})
resp.raise_for_status()
token = resp.json()["access_token"]

org_resp = requests.get(f"{base_url}/api/v1/org/memberships", headers={"Authorization": f"Bearer {token}"})
org_resp.raise_for_status()
org_id = org_resp.json()["active_org_id"]

return token, org_id


def list_safes(base_url: str, token: str, org_id: str) -> list:
resp = requests.get(
f"{base_url}/api/v1/safes",
headers={"Authorization": f"Bearer {token}", "X-Active-Org-Id": org_id},
)
resp.raise_for_status()
return resp.json()


if __name__ == "__main__":
try:
token, org_id = get_session(BASE_URL)
safes = list_safes(BASE_URL, token, org_id)
print(f"Safes ({len(safes)}):")
for s in safes:
print(f" {s.get('name', s.get('id'))}")
except requests.HTTPError as exc:
print(f"API error {exc.response.status_code}: {exc.response.text}", file=sys.stderr)
sys.exit(1)

Gestione degli errori

raise_for_status() genera requests.HTTPError su risposte 4xx/5xx. Accedi a exc.response.status_code e exc.response.text per i dettagli:

CodiceSignificato
401 UnauthorizedIl token è mancante, scaduto o non valido. Esegui nuovamente l'autenticazione.
403 ForbiddenIl token non dispone dell'ambito richiesto per questo endpoint.
429 Too Many RequestsLimite di frequenza superato. Verifica l'intestazione retry-after.
500 Internal Server ErrorErrore server transitorio. Riprova con backoff.

Consapevolezza del limite di frequenza

response = requests.get(
f"{BASE_URL}/api/v1/safes",
headers={"Authorization": f"Bearer {token}", "X-Active-Org-Id": org_id},
)
remaining = response.headers.get("x-ratelimit-remaining")
print(f"Rate limit remaining: {remaining}")

Vedi Rate Limits per le strategie di backoff.


Passaggi successivi