Overview
È possibile richiamare l'API REST di BroadNet da Python utilizzando le librerie requests o httpx. Non esiste un pacchetto BroadNet Python: l'unico SDK ufficiale è per TypeScript e Node.js, non per Python. Se si desidera un client Python tipizzato, è possibile generarne uno a partire dalle specifiche OpenAPI con openapi-generator; altrimenti, le semplici chiamate HTTP riportate di seguito sono tutto ciò che serve.
Gestione degli errori
Gli errori restituiscono un codice di stato HTTP e un corpo JSON ExceptionResponse (status, error, message, errorCode, requestUri). resp.raise_for_status() li trasforma in eccezioni. Riprova solo in caso di errori di rete e risposte 5xx, con un intervallo di tempo tra un tentativo e l'altro; una volta che una chiamata ha restituito un ID messaggio, l'invio è stato accettato, quindi non inviarlo di nuovo alla cieca.
Requisiti
Qualsiasi versione Python 3 supportata. L'esempio sincrono utilizza requests e l'esempio asincrono utilizza httpx; installate quello che utilizzate.
Esempi
Copia, incolla, sostituisci i segnaposto: questi esempi chiamano l'API di produzione così come sono.
pip install requests httpximport os, requests
r = requests.post(
"https://api.broadnet.me/sms/sendSms",
headers={"Authorization": f"Bearer {os.environ['BROADNET_TOKEN']}"},
json={
"senderId": "BroadNet",
"destinationNumber": "447700900123",
"message": "Your verification code is 482913",
"messageType": "TEXT",
},
)
print(r.status_code, r.text) # message IDimport asyncio
import os
import httpx
URL = "https://api.broadnet.me/sms/sendSms"
HEADERS = {"Authorization": f"Bearer {os.environ['BROADNET_TOKEN']}"}
async def send(client: httpx.AsyncClient, number: str, text: str) -> str:
resp = await client.post(
URL,
headers=HEADERS,
json={
"senderId": "BroadNet",
"destinationNumber": number,
"message": text,
"messageType": "TEXT",
},
)
resp.raise_for_status()
return resp.text # message ID
async def main() -> None:
recipients = ["447700900123", "447700900124", "447700900125"]
async with httpx.AsyncClient(timeout=10) as client:
ids = await asyncio.gather(
*(send(client, n, "Your code is 482913") for n in recipients)
)
print(ids)
if __name__ == "__main__":
asyncio.run(main())# Optional: generate a typed Python client from the OpenAPI spec
curl -O https://www.broadnet.me/developers/openapi.yaml
npx @openapitools/openapi-generator-cli generate \
-i openapi.yaml -g python -o broadnet-python