Skip to content

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 ​

NameImportPurpose
Clientfrom pyptp import ClientClient for the Phase to Phase cloud API
Credentialsfrom pyptp import CredentialsClient ID, secret and connection settings, read from arguments, environment variables or a .env file
TokenManagerfrom pyptp.api import TokenManagerFetches and caches OAuth2 access tokens
APIError and subclassesfrom pyptp.api import APIErrorErrors 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 ​

python
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:

VariableDefaultDescription
PYPTP_CLIENT_IDnoneYour API client ID (required)
PYPTP_CLIENT_SECRETnoneYour API client secret (required)
PYPTP_ENVIRONMENTproductionAPI environment: test, acceptance or production
PYPTP_TIMEOUT120Request timeout in seconds
PYPTP_MAX_RETRIES3Maximum retry attempts
PYPTP_VERIFY_SSLtrueWhether 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 ​

python
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 ​

python
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 ​

python
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:

EnvironmentDefault
productionyes
acceptance
test

Any other name raises APIEnvironmentError. The client exposes the chosen environment and its API address:

python
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.

python
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 call

TokenManager 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:

ExceptionRaised when
APIConfigurationErrorThe client ID or secret is missing
APIEnvironmentErrorThe environment name is not test, acceptance or production
APIAuthenticationErrorThe token endpoint cannot be reached, rejects the credentials or returns an invalid response
python
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 environments

Security Best Practices ​

Environment Variables ​

bash
# .env file (never commit to version control)
PYPTP_CLIENT_ID=your-client-id
PYPTP_CLIENT_SECRET=your-secret
PYPTP_ENVIRONMENT=acceptance
python
from pyptp import Client

client = Client()  # Reads the environment variables and .env

Credentials 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 ​

python
# 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 ​

python
# 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 ​

python
"""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='...')