Telnyx Python Library

repository·master·Indexed 41 days ago

https://github.com/team-telnyx/telnyx-python

The official Python library for the Telnyx API (v4.179.0), providing a high-level, type-safe interface for synchronous and asynchronous workflows. It includes built-in support for pagination, file uploads, and custom HTTP client configurations via httpx or aiohttp.

Tokens
72.7K
Snippets
308
Records
338
Agent score
49%

What's inside Telnyx

  1. Handle paginated list responses

    master

    List methods in the Telnyx API are paginated. The library provides auto-paginating iterators that fetch subsequent pages automatically as you iterate.

    Synchronous Auto-pagination

    from telnyx import Telnyx
    
    client = Telnyx()
    
    all_access_ip_addresses = []
    for access_ip_address in client.access_ip_address.list(
        page_number=1,
        page_size=50,
    ):
        all_access_ip_addresses.append(access_ip_address)

    Asynchronous Auto-pagination

    import asyncio
    from telnyx import AsyncTelnyx
    
    client = AsyncTelnyx()
    
    async def main() -> None:
        all_access_ip_addresses = []
        async for access_ip_address in client.access_ip_address.list(
            page_number=1,
            page_size=50,
        ):
            all_access_ip_addresses.append(access_ip_address)
        print(all_access_ip_addresses)
    
    asyncio.run(main())

    Granular Page Control

    You can also manually control pagination using .has_next_page(), .next_page_info(), or .get_next_page().

    # Manual page control example
    first_page = await client.access_ip_address.list(
        page_number=1,
        page_size=50,
    )
    if first_page.has_next_page():
        print(f"will fetch next page using these details: {first_page.next_page_info()}")
        next_page = await first_page.get_next_page()
        print(f"number of items we just fetched: {len(next_page.data)}")
  2. Differentiate between null and missing fields in API responses

    master

    In API responses, a field that is explicitly null or missing entirely will both result in a value of None in the Python library. To distinguish between an explicit null and a missing key, use the .model_fields_set attribute on the response object.

    if response.my_field is None:
      if 'my_field' not in response.model_fields_set:
        print('Got json like {}, without a "my_field" key present at all.'.format(response.model_dump()))
      else:
        print('Got json like {"my_field": null}.')
  3. Configure retries and timeouts

    master

    Retries

    Certain errors (Connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors) are automatically retried 2 times by default with exponential backoff. Use max_retries to change this.

    Timeouts

    Requests time out after 1 minute by default. You can configure this using a float or an httpx.Timeout object. On timeout, an APITimeoutError is raised.

    Use .with_options() to apply settings to specific requests without changing the global client configuration.

    from telnyx import Telnyx
    import httpx
    
    # Configure global defaults
    client = Telnyx(max_retries=0, timeout=20.0)
    
    # Configure granular global timeout
    client = Telnyx(timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0))
    
    # Override per-request
    client.with_options(max_retries=5).number_orders.create(
        phone_numbers=[{"phone_number": "+15558675309"}],
    )
    
    client.with_options(timeout=5.0).number_orders.create(
        phone_numbers=[{"phone_number": "+15558675309"}],
    )
  4. Configure the async client with aiohttp

    master

    By default, the async client uses httpx. For improved concurrency performance, you can use aiohttp as the backend by installing the telnyx[aiohttp] extra and passing DefaultAioHttpClient() to the client.

    # install from PyPI
    pip install telnyx[aiohttp]
    import os
    import asyncio
    from telnyx import DefaultAioHttpClient
    from telnyx import AsyncTelnyx
    
    
    async def main() -> None:
        async with AsyncTelnyx(
            api_key=os.environ.get("TELNYX_API_KEY"),  # This is the default and can be omitted
            http_client=DefaultAioHttpClient(),
        ) as client:
            response = await client.calls.dial(
                connection_id="conn12345",
                from="+15557654321",
                to="+15551234567",
                webhook_url="https://your-webhook.url/events",
            )
            print(response.data)
    
    
    asyncio.run(main())
  5. Enable library logging

    master

    The library uses the standard Python logging module. You can control the verbosity of the library's logs by setting the TELNYX_LOG environment variable.

    Set it to info for standard logging or debug for more verbose output.

    $ export TELNYX_LOG=info
  6. Manage HTTP resources and client lifecycle

    master

    While the library automatically closes connections when the client is garbage collected, it is best practice to manage the lifecycle manually using a context manager or by calling .close() to ensure resources are released promptly.

    from telnyx import Telnyx
    
    with Telnyx() as client:
      # make requests here
      ...
    
    # HTTP client is now closed
  7. Make custom or undocumented API requests

    master

    If you need to interact with undocumented endpoints or parameters, you can use the client's direct HTTP verb methods (client.get, client.post, etc.).

    • Undocumented Endpoints: Use client.post(path, ...) etc. Use the cast_to parameter to specify the expected response type (e.g., httpx.Response).
    • Undocumented Params: Use extra_query, extra_body, or extra_headers to send additional data.
    • Undocumented Response Properties: Access extra fields directly via response.unknown_prop or retrieve all extra fields as a dictionary using response.model_extra.
    import httpx
    
    # Undocumented endpoint
    response = client.post(
        "/foo",
        cast_to=httpx.Response,
        body={"my_param": True},
    )
    
    print(response.headers.get("x-foo"))
  8. Upload files in requests

    master

    Request parameters that accept files can be passed as bytes, a PathLike instance (e.g., pathlib.Path), or a tuple of (filename, contents, media type). When using PathLike with the async client, the file is read asynchronously.

    from pathlib import Path
    from telnyx import Telnyx
    
    client = Telnyx()
    
    client.ai.audio.transcribe(
        model="distil-whisper/distil-large-v2",
        file=Path("/path/to/file"),
    )
  9. Configure the HTTP client and proxies

    master

    You can customize the underlying httpx client by passing a DefaultHttpxClient to the Telnyx constructor. This allows you to configure proxies, custom transports, and other advanced httpx features.

    You can also override the base URL using the base_url parameter or the TELNYX_BASE_URL environment variable. For per-request customization, use the .with_options() method.

    import httpx
    from telnyx import Telnyx, DefaultHttpxClient
    
    client = Telnyx(
        # Or use the `TELNYX_BASE_URL` env var
        base_url="http://my.test.server.example.com:8083",
        http_client=DefaultHttpxClient(
            proxy="http://my.test.proxy.example.com",
            transport=httpx.HTTPTransport(local_address="0.0.0.0"),
        ),
    )
    
    # Per-request customization
    client.with_options(http_client=DefaultHttpxClient(...))
  10. Access raw or streaming responses from credential connection actions

    master

    If you need to access the raw HTTP response (e.g., to inspect headers) or handle a streaming response instead of the parsed JSON object, use the .with_raw_response or .with_streaming_response properties as prefixes to your method calls.

    • .with_raw_response: Returns a raw response object instead of the parsed content.
    • .with_streaming_response: An alternative that does not eagerly read the response body.
    # Accessing raw response to see headers
    raw_response = client.credential_connections.actions.with_raw_response.check_registration_status(id="id")
    print(raw_response.headers)
    
    # Asynchronous raw response
    raw_response = await client.async_credential_connections.actions.with_raw_response.check_registration_status(id="id")
  11. Use the asynchronous Telnyx client

    master

    Import AsyncTelnyx to perform asynchronous API calls using await. The functionality is identical to the synchronous client.

    import os
    import asyncio
    from telnyx import AsyncTelnyx
    
    client = AsyncTelnyx(
        api_key=os.environ.get("TELNYX_API_KEY"),  # This is the default and can be omitted
    )
    
    async def main() -> None:
        response = await client.calls.dial(
            connection_id="conn12345",
            from="+15557654321",
            to="+15551234567",
            webhook_url="https://your-webhook.url/events",
        )
        print(response.data)
    
    asyncio.run(main())