Skip to main content

API Client

The Synthefy Python SDK provides both synchronous and asynchronous API clients for making forecasting requests.

Synchronous Client

SynthefyAPIClient

class SynthefyAPIClient:
    def __init__(
        self,
        api_key: str | None = None,
        *,
        timeout: float = 300.0,
        max_retries: int = 2,
        base_url: str = BASE_URL,
        endpoint: str = ENDPOINT,
        organization: Optional[str] = None,
        user_agent: Optional[str] = None,
    ):
        """Initialize the Synthefy API client."""

Parameters

api_key
Type: str or None Default: None API key for authentication. If not provided, will look for SYNTHEFY_API_KEY environment variable.
timeout
Type: float Default: 300.0 Request timeout in seconds.
max_retries
Type: int Default: 2 Maximum number of retry attempts for failed requests.
base_url
Type: str Default: "https://prod.synthefy.com" Base URL for the API.
endpoint
Type: str Default: "/api/v2/foundation_models/forecast/stream" API endpoint for forecasting requests.
organization
Type: str or None Default: None Organization ID for multi-tenant setups.
user_agent
Type: str or None Default: None Custom user agent string.

Methods

forecast
def forecast(
    self,
    request: ForecastV2Request,
    *,
    timeout: Optional[float] = None,
    idempotency_key: Optional[str] = None,
    extra_headers: Optional[Dict[str, str]] = None,
) -> ForecastV2Response:
    """Make a direct forecasting request."""
forecast_dfs
def forecast_dfs(
    self,
    history_dfs: List[pd.DataFrame],
    target_dfs: List[pd.DataFrame],
    target_col: str,
    timestamp_col: str,
    metadata_cols: List[str],
    leak_cols: List[str],
    model: str,
) -> List[pd.DataFrame]:
    """Make a forecasting request using pandas DataFrames."""

Asynchronous Client

SynthefyAsyncAPIClient

class SynthefyAsyncAPIClient:
    def __init__(
        self,
        api_key: str | None = None,
        *,
        timeout: float = 300.0,
        max_retries: int = 2,
        base_url: str = BASE_URL,
        endpoint: str = ENDPOINT,
        organization: Optional[str] = None,
        user_agent: Optional[str] = None,
    ):
        """Initialize the async Synthefy API client."""

Methods

forecast
async def forecast(
    self,
    request: ForecastV2Request,
    *,
    timeout: Optional[float] = None,
    idempotency_key: Optional[str] = None,
    extra_headers: Optional[Dict[str, str]] = None,
) -> ForecastV2Response:
    """Make a direct async forecasting request."""
forecast_dfs
async def forecast_dfs(
    self,
    history_dfs: List[pd.DataFrame],
    target_dfs: List[pd.DataFrame],
    target_col: str,
    timestamp_col: str,
    metadata_cols: List[str],
    leak_cols: List[str],
    model: str,
) -> List[pd.DataFrame]:
    """Make an async forecasting request using pandas DataFrames."""

Error Classes

SynthefyError

Base error for all Synthefy client exceptions.

APITimeoutError

The request timed out before completing.

APIConnectionError

The request failed due to a connection issue.

APIStatusError

Raised when the API returns a non-2xx status code.

BadRequestError

Invalid request data (400, 422 status codes).

AuthenticationError

Invalid API key (401 status code).

PermissionDeniedError

Access denied (403 status code).

NotFoundError

Resource not found (404 status code).

RateLimitError

Rate limit exceeded (429 status code).

InternalServerError

Server error (5xx status codes).

Examples

Basic Synchronous Usage

import pandas as pd
import numpy as np
from synthefy import SynthefyAPIClient

# Create sample data
history_data = pd.DataFrame({
    'date': pd.date_range('2024-01-01', periods=100, freq='D'),
    'sales': np.random.normal(100, 10, 100),
    'store_id': 1,
    'category_id': 101
})

target_data = pd.DataFrame({
    'date': pd.date_range('2024-04-11', periods=30, freq='D'),
    'sales': np.nan,  # Values to forecast
    'store_id': 1,
    'category_id': 101
})

# Make forecast
with SynthefyAPIClient() as client:
    forecast_dfs = client.forecast_dfs(
        history_dfs=[history_data],
        target_dfs=[target_data],
        target_col='sales',
        timestamp_col='date',
        metadata_cols=['store_id', 'category_id'],
        leak_cols=[],
        model='synthefy-fm'
    )

print(forecast_dfs[0].head())

Asynchronous Usage

import asyncio
import pandas as pd
import numpy as np
from synthefy import SynthefyAsyncAPIClient

async def main():
    # Create sample data
    history_data = pd.DataFrame({
        'date': pd.date_range('2024-01-01', periods=100, freq='D'),
        'sales': np.random.normal(100, 10, 100),
        'store_id': 1,
        'category_id': 101
    })

    target_data = pd.DataFrame({
        'date': pd.date_range('2024-04-11', periods=30, freq='D'),
        'sales': np.nan,
        'store_id': 1,
        'category_id': 101
    })

    # Make async forecast
    async with SynthefyAsyncAPIClient() as client:
        forecast_dfs = await client.forecast_dfs(
            history_dfs=[history_data],
            target_dfs=[target_data],
            target_col='sales',
            timestamp_col='date',
            metadata_cols=['store_id', 'category_id'],
            leak_cols=[],
            model='synthefy-fm'
        )

    print(forecast_dfs[0].head())

# Run the async function
asyncio.run(main())

Error Handling

from synthefy import SynthefyAPIClient, BadRequestError, RateLimitError, APITimeoutError

try:
    with SynthefyAPIClient() as client:
        forecast_dfs = client.forecast_dfs(
            history_dfs=[history_df],
            target_dfs=[target_df],
            target_col='sales',
            timestamp_col='date',
            metadata_cols=['store_id'],
            leak_cols=[],
            model='synthefy-fm'
        )
except BadRequestError as e:
    print(f"Invalid request: {e}")
    print(f"Status code: {e.status_code}")
except RateLimitError as e:
    print(f"Rate limited: {e}")
    # Client automatically retries with exponential backoff
except APITimeoutError as e:
    print(f"Request timed out: {e}")

See Also