Authy Python API Client
The `authy` library is the official Python client for the Authy API, providing functionalities for two-factor authentication, including user registration, token verification, and sending SMS or push notifications. As of version 2.2.6, it offers a stable interface to integrate Authy's services into Python applications, supporting Python 3.6+. Its release cadence is low, focusing on stability and maintenance.
Common errors
-
ModuleNotFoundError: No module named 'authy'
cause The 'authy' library is not installed in the Python environment.fixInstall the 'authy' package using pip: 'pip install authy'. -
ImportError: cannot import name 'to_native_string'
cause The 'requests' library version is outdated and lacks the 'to_native_string' function.fixUpgrade the 'requests' library to the latest version using pip: 'pip install --upgrade requests'. -
AttributeError: module 'authy' has no attribute 'AuthyApiClient'
cause Incorrect import statement or outdated 'authy' library version.fixEnsure the correct import statement: 'from authy.api import AuthyApiClient'. If the issue persists, upgrade the 'authy' library: 'pip install --upgrade authy'. -
TypeError: 'NoneType' object is not subscriptable
cause The 'authy' API client returned 'None', possibly due to an invalid API key or network issue.fixVerify the API key is correct and has the necessary permissions. Check network connectivity and ensure the Authy service is operational. -
ValueError: Invalid TOTP token
cause The provided TOTP token does not match the expected value, possibly due to time synchronization issues.fixEnsure the server and client devices have synchronized clocks. Verify the TOTP generation parameters (e.g., time step, algorithm) match between the server and client.
Warnings
- gotcha Authy API calls return response objects that require explicit checking with `.ok()` to determine success or failure. Direct access to `.content` without checking `.ok()` first can lead to processing error messages as valid data.
- gotcha The library uses a single API key for all operations. Ensure you are using the correct API key (e.g., 'production' vs. 'sandbox') for your target environment. Mixing them will lead to `AuthyException` or unexpected behavior (e.g., users not found).
- gotcha Authy IDs are internal to Authy and distinct from your application's user IDs. You must first register a user with Authy (`authy_api.users.create`) to obtain an `authy_id` before performing other user-specific operations like sending tokens or verifying.
- gotcha The `authy` client's methods (`users`, `tokens`, `phones`) return specific response objects. Accessing data like an Authy ID, status, or verification result often requires drilling into the `.content` attribute, which is a dictionary (e.g., `user_registration_response.content['user']['id']`).
Install
-
pip install authy
Imports
- AuthyApiClient
from authy import AuthyApiClient
- AuthyException
from authy.authy_exceptions import AuthyException
Quickstart
import os
from authy import AuthyApiClient
from authy.authy_exceptions import AuthyException
# IMPORTANT: Replace 'YOUR_AUTHY_API_KEY_HERE' with your actual Authy API key
# or, preferably, set it as an environment variable: export AUTHY_API_KEY='...'
api_key = os.environ.get('AUTHY_API_KEY', 'YOUR_AUTHY_API_KEY_HERE')
if api_key == 'YOUR_AUTHY_API_KEY_HERE' or not api_key:
print("WARNING: Please set the AUTHY_API_KEY environment variable "
"or replace 'YOUR_AUTHY_API_KEY_HERE' with your actual key to run this example.")
# In a real application, you might raise an error or handle this differently.
# For a runnable quickstart, we'll try to proceed but expect failures if key is invalid.
try:
authy_api = AuthyApiClient(api_key)
# --- Example 1: Check User Status (requires an existing Authy ID) ---
# Replace with an actual Authy ID from a user registered in your Authy app.
# If using a dummy ID, this call will likely fail with a "User not found" error.
sample_authy_id = "1234567" # Example: Replace with a real Authy ID if you have one
print(f"\n--- Attempting to get status for Authy ID: {sample_authy_id} ---")
user_status_response = authy_api.users.status(sample_authy_id)
if user_status_response.ok():
print(f"SUCCESS: User {sample_authy_id} status: {user_status_response.content}")
# Example of accessing content: user_status_response.content['user']['status']
else:
print(f"FAILURE: Could not get user status. Errors: {user_status_response.errors()}")
print(f"Full API response content: {user_status_response.content}")
# --- Example 2: Verify a 2FA Token (requires an existing Authy ID and a token) ---
# Replace with a real Authy ID and a real token generated for that user.
# If using dummy values, this call will likely fail with "invalid token" or "user not found".
sample_token_authy_id = sample_authy_id # Use the same dummy ID for consistency
sample_token_code = "0000000" # Example: Replace with a real 2FA token
print(f"\n--- Attempting to verify token '{sample_token_code}' for Authy ID: {sample_token_authy_id} ---")
token_verification_response = authy_api.tokens.verify(sample_token_authy_id, sample_token_code)
if token_verification_response.ok():
print(f"SUCCESS: Token '{sample_token_code}' verified for Authy ID {sample_token_authy_id}.")
# Example of accessing content: token_verification_response.content['token']['message']
else:
print(f"FAILURE: Token verification failed. Errors: {token_verification_response.errors()}")
print(f"Full API response content: {token_verification_response.content}")
except AuthyException as e:
print(f"\nAn Authy API specific error occurred: {e}")
except Exception as e:
print(f"\nAn unexpected error occurred: {e}")
print("\n--- Quickstart example finished ---")