API Client
This guide covers configuring the Phase to Phase API client and its OAuth2 authentication.
Preview
The cloud API is not public yet. In pyptp 0.46.0 the Client sets up credentials, the environment and token handling, but it has no methods for remote network operations. To ask about API access and client credentials, contact [email protected].
Full Example
View the complete code: 05_api_client.py
Overview
| Name | Import | Purpose |
|---|---|---|
Client | from pyptp import Client | Client for the Phase to Phase cloud API |
Credentials | from pyptp import Credentials | Client ID, secret and connection settings, read from arguments, environment variables or a .env file |
TokenManager | from pyptp.api import TokenManager | Fetches and caches OAuth2 access tokens |
APIError and subclasses | from pyptp.api import APIError | Errors raised by the client |
Creating a Client never contacts the server. It checks that a client ID and secret are present and that the environment name is known, then stores the environment and its base URL.
Initialization Methods
Method 1: Environment Variables (Recommended)
from pyptp import Client
# Requires PYPTP_CLIENT_ID and PYPTP_CLIENT_SECRET environment variables
client = Client()This is the recommended approach for production deployments. Credentials stay out of source code. Without a client ID and secret, Client() raises APIConfigurationError.
Environment variables:
| Variable | Default | Description |
|---|---|---|
PYPTP_CLIENT_ID | none | Your API client ID (required) |
PYPTP_CLIENT_SECRET | none | Your API client secret (required) |
PYPTP_ENVIRONMENT | production | API environment: test, acceptance or production |
PYPTP_TIMEOUT | 120 | Request timeout in seconds |
PYPTP_MAX_RETRIES | 3 | Maximum retry attempts |
PYPTP_VERIFY_SSL | true | Whether to verify SSL certificates |
PYPTP_TIMEOUT, PYPTP_MAX_RETRIES and PYPTP_VERIFY_SSL are read and stored, but they have no effect until the client makes API requests.
Method 2: Credentials Object
from pyptp import Client, Credentials
creds = Credentials(client_id="your-client-id", client_secret="your-secret")
client = Client(credentials=creds)Useful when credentials come from a secrets manager or configuration system. Credentials accepts the same settings as the environment variables, without the PYPTP_ prefix: client_id, client_secret, environment, timeout, max_retries and verify_ssl. Any setting you leave out is still read from the environment variables or the .env file.
Method 3: Direct Parameters
from pyptp import Client
client = Client(client_id="your-client-id", client_secret="your-secret")Convenient for scripts and development, but avoid hardcoding secrets in production code. The keyword arguments client_id, client_secret, environment, timeout and max_retries override the matching values from credentials or the environment.
Method 4: Environment-Specific
from pyptp import Client
client = Client.for_environment(
"acceptance",
client_id="your-client-id",
client_secret="your-secret",
)Use this when targeting a different API environment. It is the same as Client(environment="acceptance", ...) and also accepts timeout and max_retries.
Available environments:
| Environment | Default |
|---|---|
production | yes |
acceptance | |
test |
Any other name raises APIEnvironmentError. The client exposes the chosen environment and its API address:
print(client.environment) # "acceptance"
print(client.base_url)Authentication
The API uses OAuth2 client credentials. TokenManager fetches an access token from the environment's token endpoint, caches it and fetches a new one shortly before it expires. It is safe to share between threads.
from pyptp.api import TokenManager
tokens = TokenManager(
client_id="your-client-id",
client_secret="your-secret",
environment="acceptance",
)
token = tokens.get_valid_token() # contacts the token endpoint on first use
print(tokens.token_expires_at) # expiry time in UTC, None before the first token
tokens.invalidate_token() # force a new token on the next callTokenManager takes the same credentials, client_id, client_secret and environment arguments as Client, and exposes environment, base_url and token_url.
Token Management
The Client keeps its own TokenManager for the requests it will make, so you do not need to manage tokens to use the client.
Error Handling
All client errors derive from APIError:
| Exception | Raised when |
|---|---|
APIConfigurationError | The client ID or secret is missing |
APIEnvironmentError | The environment name is not test, acceptance or production |
APIAuthenticationError | The token endpoint cannot be reached, rejects the credentials or returns an invalid response |
from pyptp import Client
from pyptp.api import APIConfigurationError, APIEnvironmentError
try:
client = Client()
except APIConfigurationError:
print("Set PYPTP_CLIENT_ID and PYPTP_CLIENT_SECRET first")
except APIEnvironmentError as e:
print(e) # names the valid environmentsSecurity Best Practices
Environment Variables
# .env file (never commit to version control)
PYPTP_CLIENT_ID=your-client-id
PYPTP_CLIENT_SECRET=your-secret
PYPTP_ENVIRONMENT=acceptancefrom pyptp import Client
client = Client() # Reads the environment variables and .envCredentials reads a .env file in the current working directory by itself, so no extra package is needed. Environment variables take precedence over the .env file.
Secrets Managers
# AWS Secrets Manager example
import json
import boto3
from pyptp import Client
def get_pyptp_client():
sm = boto3.client("secretsmanager")
secret = json.loads(
sm.get_secret_value(SecretId="pyptp-credentials")["SecretString"]
)
return Client(
client_id=secret["client_id"],
client_secret=secret["client_secret"],
)Configuration Files
# config.yaml (encrypted or restricted access)
# pyptp:
# client_id: your-client-id
# client_secret: your-secret
# environment: acceptance
import yaml
from pyptp import Client
with open("config.yaml") as f:
config = yaml.safe_load(f)
client = Client(**config["pyptp"])Complete Example
"""API Client Usage Examples.
Shows different ways to initialize the Phase to Phase API client.
"""
from pyptp import Client, Credentials
# Method 1: From environment variables
# Requires PYPTP_CLIENT_ID and PYPTP_CLIENT_SECRET set in environment
client = Client()
# Method 2: Using Credentials object
creds = Credentials(client_id="your-client-id", client_secret="your-secret")
client = Client(credentials=creds)
# Method 3: Direct parameters
client = Client(client_id="your-client-id", client_secret="your-secret")
# Method 4: For specific environment (acceptance/test/production)
client = Client.for_environment(
"acceptance",
client_id="your-client-id",
client_secret="your-secret",
)
print(client) # Client(environment='acceptance', base_url='...')