Python SDK
The Authgate Python SDK is a single-file client library that you can drop directly into your Python application.
Installation
- Download
authgate_api.pyfrom your Authgate purchase - Copy it into your project directory
- Import it in your code
Requirements:
- Python 3.9 or higher
cryptographypackage (for file decryption)
pip install cryptographyQuick Start
from authgate_api import AuthgateAPI, TokenAuthStrategy
# Initialize the client
client = AuthgateAPI(
base_url="https://your-authgate.com/api/integration",
api_key="your-api-key",
api_secret="your-api-secret",
files_encryption_key="your-base64-encryption-key",
request_signing_key="your-base64-signing-key",
request_signing_enabled=True,
response_signing_key="your-base64-response-signing-key",
response_signing_enabled=True
)
# Login with username and password
auth = TokenAuthStrategy(username="user", password="pass")
client.login(auth)
# Get app context
app_context = client.get_app_context()
print(f"Connected to: {app_context.application.name}")
# Check if user has active membership
if app_context.user and app_context.user.membership.is_active:
print("User has active membership!")Authentication
The SDK supports two authentication strategies:
TokenAuthStrategy (Recommended)
Gets a session token on login and automatically refreshes it when needed.
# Login with username/password
auth = TokenAuthStrategy(username="user", password="pass")
client.login(auth)
# Login with license code
auth = TokenAuthStrategy(license_code="LICENSE-CODE")
client.login(auth)
# Login with device authentication (if enabled)
auth = TokenAuthStrategy(
username="user",
password="pass",
hardware_id="device-hardware-id"
)
client.login(auth)LegacyAuthStrategy
Sends credentials with every request. Less efficient but simpler.
from authgate_api import LegacyAuthStrategy
auth = LegacyAuthStrategy(username="user", password="pass")
client.login(auth)Common Operations
Check Membership Status
app_context = client.get_app_context()
if app_context.user and app_context.user.membership.is_active:
# User has access
pass
else:
# Show upgrade prompt
passShow Remaining Time
app_context = client.get_app_context()
membership = app_context.user.membership
if membership.is_lifetime:
print("Lifetime access")
else:
# remaining_time() compares active_until against the server's clock,
# so it isn't affected by a wrong or tampered device clock.
remaining = membership.remaining_time(app_context.server_time)
print(f"Time remaining: {remaining}") # None for lifetime, 0 when expiredActivate a License
try:
adjustment = client.activate_license(
code="LICENSE-CODE",
username="user",
password="pass"
)
if adjustment.grants_lifetime_access:
print("Lifetime license activated!")
elif adjustment.minutes:
print(f"Added {adjustment.minutes} minutes")
except ValidationError as e:
print("Invalid license code")Download Files
# Download and decrypt a file
file_data = client.download_file(
file_id="file-uuid",
decrypt=True,
output_path="config.json" # Optional: save to disk
)Access Server Variables
app_context = client.get_app_context()
for variable in app_context.application.variables:
print(f"{variable.name}: {variable.value}")Access Announcements
The app context contains announcements that are currently published and visible. Content is provided as HTML for your application to display.
app_context = client.get_app_context()
for announcement in app_context.announcements:
print(announcement.title)
print(announcement.content_html)Call get_app_context() again to refresh the list. See Announcements for publication and scheduling options.
User Variables
Store and retrieve per-user data that syncs across devices:
# Set a user variable (creates if doesn't exist)
client.set_user_variable("theme", "dark")
# Get a single user variable
theme = client.get_user_variable("theme")
# List all user variables
variables = client.get_user_variables()
for var in variables:
print(f"{var.name}: {var.value}")Error Handling
The SDK uses specific exceptions for different error types:
from authgate_api import (
AuthgateApiError,
AuthenticationError,
AuthorizationError,
TimedOutError,
ValidationError,
NetworkError
)
try:
client.get_app_context()
except AuthenticationError as e:
print("Authentication failed - wrong credentials or not logged in")
except TimedOutError as e:
print(f"Access paused until {e.get_timed_out_until()}")
if e.get_reason():
print(f"Reason: {e.get_reason()}")
except AuthorizationError as e:
# Check specific error code
error_code = e.get_error_code()
if error_code == "BANNED":
print("Account banned")
elif error_code == "INACTIVE_MEMBERSHIP":
print("Membership expired")
else:
print("Access denied")
except ValidationError as e:
# Get field-specific errors
for error in e.get_validation_errors():
print(f"{error['field']}: {error['message']}")
except NetworkError as e:
print("Connection failed")
except AuthgateApiError as e:
print(f"API error: {e}")Catch TimedOutError before AuthorizationError. It provides the ISO 8601 expiry time and the optional reason entered by the admin.
Device Authentication
If device authentication is enabled on your application, you must provide a hardware_id when logging in or signing up:
During Login:
# Generate a unique hardware ID for this device
import uuid
hardware_id = str(uuid.getnode()) # MAC address
auth = TokenAuthStrategy(
username="user",
password="pass",
hardware_id=hardware_id
)
client.login(auth)During Sign-Up:
# Sign up with username/password and register device
hardware_id = str(uuid.getnode())
user = client.sign_up("username", "password", hardware_id=hardware_id)
# Sign up with license code and register device
user = client.sign_up_with_license_code("LICENSE-CODE", hardware_id=hardware_id)API Reference
AuthgateAPI Class
Constructor:
AuthgateAPI(
base_url: str, # Your Authgate API URL
api_key: str, # Application API key
api_secret: str, # Application API secret
files_encryption_key: str, # Base64 encryption key
request_signing_key: str, # Base64 signing key
request_signing_enabled: bool,
response_signing_key: str, # Base64 response signing key
response_signing_enabled: bool,
verify_ssl: bool = True # Set False for self-signed certs
)Methods:
login(auth_strategy)- Authenticate userlogout()- Clear authenticationget_app_context()- Get application, announcements, and user infosign_up(username, password, hardware_id=None)- Create new user accountsign_up_with_license_code(code, hardware_id=None)- Create account with licenseactivate_license(code, username, password)- Activate a licensedownload_file(file_id, decrypt=True, output_path=None)- Download a fileget_user_variable(name)- Get a user variable by nameset_user_variable(name, value)- Set a user variableget_user_variables()- List all user variables
Complete Example
from authgate_api import (
AuthgateAPI,
TokenAuthStrategy,
AuthenticationError,
AuthorizationError
)
def main():
# Initialize client
client = AuthgateAPI(
base_url="https://auth.myapp.com/api/integration",
api_key="...",
api_secret="...",
files_encryption_key="...",
request_signing_key="...",
request_signing_enabled=True,
response_signing_key="...",
response_signing_enabled=True
)
try:
# Login
auth = TokenAuthStrategy(username="user", password="pass")
client.login(auth)
# Check access
context = client.get_app_context()
if context.user.membership.is_active:
print("Welcome to the app!")
# Download config file
client.download_file(
file_id=context.application.files[0].id,
output_path="config.json"
)
else:
print("Please purchase a license")
except AuthenticationError:
print("Login failed - wrong credentials")
except AuthorizationError:
print("Access denied - inactive membership")
if __name__ == "__main__":
main()