Skip to main content

Python Client SDK for Apex Ascend Platform

Project description

Introducing the Apex Python SDK

In today's fast-paced digital ecosystem, developers need tools that not only streamline the development process but also unlock new possibilities for innovation and efficiency.

Enter the Apex Python SDK, a cutting-edge software development kit designed to empower fintech app developers like never before. With our SDK, you can more easily integrate new account creation, optimize trading, and elevate your applications with realtime buying power, all through a seamless, SDK interface.

Whether you're building complex, data-driven platforms or simplified, user-centric applications, Apex Python SDK was created to offer the flexibility, power, and ease of use to bring your visions to life faster and more effectively. Join us in redefining the boundaries of what your applications can achieve. Start your journey with Apex today.

SDK Installation

PIP

pip install ascend-sdk

Poetry

poetry add ascend-sdk

Supported Python Versions

  • Python 3.9 or later

Initializing the SDK

The following sample shows how to initialise the SDK, using the API Key and Service Account Credentials you received during sign-up:

from ascend_sdk import SDK
from ascend_sdk.models import components

s = SDK(
    security=components.Security(
        api_key="ABCDEFGHIJ0123456789abcdefghij0123456789",
        service_account_creds=components.ServiceAccountCreds(
            private_key="-----BEGIN PRIVATE KEY--{OMITTED FOR BREVITY}",
            name="FinFirm",
            organization="correspondents/00000000-0000-0000-0000-000000000000",
            type="serviceAccount",
        ),
    ),
)

# With an instance of the SDK, invoke any operation e.g.
resp = s.account_creation.get_account(account_id="VALID_ACCOUNT_ID")

Error Handling

SDKBaseError is the base class for all HTTP error responses. It has the following properties:

Property Type Description
err.message str Error message
err.status_code int HTTP response status code eg 404
err.headers httpx.Headers HTTP response headers
err.body str HTTP body. Can be empty string if no body is returned.
err.raw_response httpx.Response Raw HTTP response
err.data Optional. Some errors may contain structured data. See Error Classes.

Example

from ascend_sdk import SDK
from ascend_sdk.models import components, errors, operations


with SDK(
    security=components.Security(
        api_key="ABCDEFGHIJ0123456789abcdefghij0123456789",
        service_account_creds=components.ServiceAccountCreds(
            private_key="-----BEGIN PRIVATE KEY--{OMITTED FOR BREVITY}",
            name="FinFirm",
            organization="correspondents/00000000-0000-0000-0000-000000000000",
            type="serviceAccount",
        ),
    ),
) as sdk:
    res = None
    try:

        res = sdk.account_creation.get_account(account_id="01HC3MAQ4DR9QN1V8MJ4CN1HMK", view=operations.QueryParamView.FULL)

        assert res.account is not None

        # Handle response
        print(res.account)


    except errors.SDKBaseError as e:
        # The base class for HTTP error responses
        print(e.message)
        print(e.status_code)
        print(e.body)
        print(e.headers)
        print(e.raw_response)

        # Depending on the method different errors may be thrown
        if isinstance(e, errors.Status):
            print(e.data.code)  # Optional[int]
            print(e.data.details)  # Optional[List[components.AnyT]]
            print(e.data.message)  # Optional[str]

Error Classes

Primary errors:

  • SDKBaseError: The base class for HTTP error responses.
    • Status: The status message serves as the general-purpose service error message. Each status message includes a gRPC error code, error message, and error details. *
Less common errors (5)

Network errors:

Inherit from SDKBaseError:

  • ResponseValidationError: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via the cause attribute.

* Check the method documentation to see if the error is applicable.

Server Selection

Select Server by Name

You can override the default server globally by passing a server name to the server: str optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:

Name Server Description
uat https://uat.apexapis.com our uat environment
prod https://api.apexapis.com our production environment
sbx https://sbx.apexapis.com our sandbox environment

Example

from ascend_sdk import SDK
from ascend_sdk.models import components, operations


with SDK(
    server="sbx",
    security=components.Security(
        api_key="ABCDEFGHIJ0123456789abcdefghij0123456789",
        service_account_creds=components.ServiceAccountCreds(
            private_key="-----BEGIN PRIVATE KEY--{OMITTED FOR BREVITY}",
            name="FinFirm",
            organization="correspondents/00000000-0000-0000-0000-000000000000",
            type="serviceAccount",
        ),
    ),
) as sdk:

    res = sdk.account_creation.get_account(account_id="01HC3MAQ4DR9QN1V8MJ4CN1HMK", view=operations.QueryParamView.FULL)

    assert res.account is not None

    # Handle response
    print(res.account)

Override Server URL Per-Client

The default server can also be overridden globally by passing a URL to the server_url: str optional parameter when initializing the SDK client instance. For example:

from ascend_sdk import SDK
from ascend_sdk.models import components, operations


with SDK(
    server_url="https://uat.apexapis.com",
    security=components.Security(
        api_key="ABCDEFGHIJ0123456789abcdefghij0123456789",
        service_account_creds=components.ServiceAccountCreds(
            private_key="-----BEGIN PRIVATE KEY--{OMITTED FOR BREVITY}",
            name="FinFirm",
            organization="correspondents/00000000-0000-0000-0000-000000000000",
            type="serviceAccount",
        ),
    ),
) as sdk:

    res = sdk.account_creation.get_account(account_id="01HC3MAQ4DR9QN1V8MJ4CN1HMK", view=operations.QueryParamView.FULL)

    assert res.account is not None

    # Handle response
    print(res.account)

Custom HTTP Client

The Python SDK makes API calls using the httpx HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance. Depending on whether you are using the sync or async version of the SDK, you can pass an instance of HttpClient or AsyncHttpClient respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls. This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of httpx.Client or httpx.AsyncClient directly.

For example, you could specify a header for every request that this sdk makes as follows:

from ascend_sdk import SDK
import httpx

http_client = httpx.Client(headers={"x-custom-header": "someValue"})
s = SDK(client=http_client)

or you could wrap the client with your own custom logic:

from ascend_sdk import SDK
from ascend_sdk.httpclient import AsyncHttpClient
import httpx

class CustomClient(AsyncHttpClient):
    client: AsyncHttpClient

    def __init__(self, client: AsyncHttpClient):
        self.client = client

    async def send(
        self,
        request: httpx.Request,
        *,
        stream: bool = False,
        auth: Union[
            httpx._types.AuthTypes, httpx._client.UseClientDefault, None
        ] = httpx.USE_CLIENT_DEFAULT,
        follow_redirects: Union[
            bool, httpx._client.UseClientDefault
        ] = httpx.USE_CLIENT_DEFAULT,
    ) -> httpx.Response:
        request.headers["Client-Level-Header"] = "added by client"

        return await self.client.send(
            request, stream=stream, auth=auth, follow_redirects=follow_redirects
        )

    def build_request(
        self,
        method: str,
        url: httpx._types.URLTypes,
        *,
        content: Optional[httpx._types.RequestContent] = None,
        data: Optional[httpx._types.RequestData] = None,
        files: Optional[httpx._types.RequestFiles] = None,
        json: Optional[Any] = None,
        params: Optional[httpx._types.QueryParamTypes] = None,
        headers: Optional[httpx._types.HeaderTypes] = None,
        cookies: Optional[httpx._types.CookieTypes] = None,
        timeout: Union[
            httpx._types.TimeoutTypes, httpx._client.UseClientDefault
        ] = httpx.USE_CLIENT_DEFAULT,
        extensions: Optional[httpx._types.RequestExtensions] = None,
    ) -> httpx.Request:
        return self.client.build_request(
            method,
            url,
            content=content,
            data=data,
            files=files,
            json=json,
            params=params,
            headers=headers,
            cookies=cookies,
            timeout=timeout,
            extensions=extensions,
        )

s = SDK(async_client=CustomClient(httpx.AsyncClient()))

IDE Support

PyCharm

Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin.

Available Resources and Operations

Available methods

account_creation

account_management

account_transfers

ach_transfers

alternative_account_accreditation

alternative_investment_documents

alternative_investments

alternative_orders

asset_trading_config

assets

authentication

bank_relationships

basket_orders

buying_power

cash_balances

checks

data_retrieval

enrollments_and_agreements

fees_and_credits

fixed_income_pricing

instant_cash_transfer_ict

investigations

investor_docs

journals

ledger

option_instructions

option_orders

orders

person_management

position_journals

pre_ipo_companies

pre_ipo_funding_rounds

pre_ipo_news_events

pre_ipo_research_documents

reader

retirements

schedule_transfers

subscriber

test_simulation

trade_allocation

trade_booking

wires

Pagination

Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the returned response object will have a Next method that can be called to pull down the next group of results. If the return value of Next is None, then there are no more pages to be fetched.

Here's an example of one such pagination call:

from ascend_sdk import SDK
from ascend_sdk.models import operations


with SDK() as sdk:

    res = sdk.authentication.list_signing_keys(security=operations.AuthenticationListSigningKeysSecurity(
        api_key_auth="<YOUR_API_KEY_HERE>",
    ), page_size=50, page_token="ZXhhbXBsZQo")

    while res is not None:
        # Handle items

        res = res.next()

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a RetryConfig object to the call:

from ascend_sdk import SDK
from ascend_sdk.models import operations
from ascend_sdk.utils import BackoffStrategy, RetryConfig


with SDK() as sdk:

    res = sdk.authentication.generate_service_account_token(security=operations.AuthenticationGenerateServiceAccountTokenSecurity(
        api_key_auth="<YOUR_API_KEY_HERE>",
    ), request={
        "jws": "eyJhbGciOiAiUlMyNTYifQ.eyJuYW1lIjogImpkb3VnaCIsIm9yZ2FuaXphdGlvbiI6ICJjb3JyZXNwb25kZW50cy8xMjM0NTY3OC0xMjM0LTEyMzQtMTIzNC0xMjM0NTY3ODkxMDEiLCJkYXRldGltZSI6ICIyMDI0LTAyLTA1VDIxOjAyOjI3LjkwMTE4MFoifQ.IMy3KmYoG8Ppf+7hXN7tm7J4MrNpQLGL7WCWvhh4nZWAVKkluL3/u3KC6hZ6Mb/5p7Y54CgZ68aWT2BcP5y4VtzIZR1Chm5pxbLfgE4aJuk+FnF6K3Gc3bBjOWCL58pxY2aTb0iU/exDEA1cbMDvbCzmY5kRefDvorLOqgUS/tS2MJ2jv4RlZFPlmHv5PtOruJ8xUW19gEgGhsPXYYeSHFTE1ZlaDvyXrKtpOvlf+FVc2RTuEw529LZnzwH4/eJJR3BpSpHyJTjQqiaMT3wzpXXYKfCRqnDkSSKJDzCzTb0/uWK/Lf0uafxPXk5YLdis+dbo1zNQhVVKjwnMpk1vLw",
    },
        RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))

    assert res.token is not None

    # Handle response
    print(res.token)

If you'd like to override the default retry strategy for all operations that support retries, you can use the retry_config optional parameter when initializing the SDK:

from ascend_sdk import SDK
from ascend_sdk.models import operations
from ascend_sdk.utils import BackoffStrategy, RetryConfig


with SDK(
    retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
) as sdk:

    res = sdk.authentication.generate_service_account_token(security=operations.AuthenticationGenerateServiceAccountTokenSecurity(
        api_key_auth="<YOUR_API_KEY_HERE>",
    ), request={
        "jws": "eyJhbGciOiAiUlMyNTYifQ.eyJuYW1lIjogImpkb3VnaCIsIm9yZ2FuaXphdGlvbiI6ICJjb3JyZXNwb25kZW50cy8xMjM0NTY3OC0xMjM0LTEyMzQtMTIzNC0xMjM0NTY3ODkxMDEiLCJkYXRldGltZSI6ICIyMDI0LTAyLTA1VDIxOjAyOjI3LjkwMTE4MFoifQ.IMy3KmYoG8Ppf+7hXN7tm7J4MrNpQLGL7WCWvhh4nZWAVKkluL3/u3KC6hZ6Mb/5p7Y54CgZ68aWT2BcP5y4VtzIZR1Chm5pxbLfgE4aJuk+FnF6K3Gc3bBjOWCL58pxY2aTb0iU/exDEA1cbMDvbCzmY5kRefDvorLOqgUS/tS2MJ2jv4RlZFPlmHv5PtOruJ8xUW19gEgGhsPXYYeSHFTE1ZlaDvyXrKtpOvlf+FVc2RTuEw529LZnzwH4/eJJR3BpSpHyJTjQqiaMT3wzpXXYKfCRqnDkSSKJDzCzTb0/uWK/Lf0uafxPXk5YLdis+dbo1zNQhVVKjwnMpk1vLw",
    })

    assert res.token is not None

    # Handle response
    print(res.token)

Resource Management

The SDK class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a context manager and reuse it across the application.

from ascend_sdk import SDK
def main():

    with SDK() as sdk:
        # Rest of application here...


# Or when using async:
async def amain():

    async with SDK() as sdk:
        # Rest of application here...

Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass your own logger class directly into your SDK.

from ascend_sdk import SDK
import logging

logging.basicConfig(level=logging.DEBUG)
s = SDK(debug_logger=logging.getLogger("ascend_sdk"))

Qase TestOps Integration

Test results can be automatically reported to Qase TestOps for centralized visibility.

Environment Variables

Variable Description
QASE_MODE Set to testops to enable reporting (default: off)
QASE_TESTOPS_API_TOKEN Qase API token for authentication
QASE_TESTOPS_PROJECT Qase project code (default: CDX)

Running Tests with Qase Reporting

# Without Qase (default)
.venv/bin/pytest tests/ -v

# With Qase reporting enabled
QASE_MODE=testops QASE_TESTOPS_API_TOKEN=<token> .venv/bin/pytest tests/ -v

Qase reporting is disabled by default via addopts = "--qase-mode=off" in pyproject.toml. Setting QASE_MODE=testops as an environment variable overrides this.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ascend_sdk-1.8.6-py3-none-any.whl (1.2 MB view details)

Uploaded Python 3

File details

Details for the file ascend_sdk-1.8.6-py3-none-any.whl.

File metadata

  • Download URL: ascend_sdk-1.8.6-py3-none-any.whl
  • Upload date:
  • Size: 1.2 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for ascend_sdk-1.8.6-py3-none-any.whl
Algorithm Hash digest
SHA256 cbcbcdcb7111cada04fcaff61487382abf241ace9d191f08f5e3c868399857bb
MD5 6d48a9dbaeeef533ebb585540513b262
BLAKE2b-256 29658d0eba37eb840a8aaee33ee2b6d86eb6ce26e253c4e5512188b6d18c2ef4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page