Skip to content

FastPix/fastpix-python

Repository files navigation

Python SDK

Developer‑friendly and type‑safe Python SDK specifically catered to leverage fastpix_python API.

Introduction

The FastPix Python SDK simplifies integration with the FastPix platform. It provides a clean, Pythonic interface for secure and efficient communication with the FastPix API, enabling easy management of media uploads, live streaming, on‑demand content, playlists, video analytics, and signing keys for secure access and token management. It is intended for use with Python 3.8 and above.

Prerequisites

Environment and Version Support

Requirement Version Description
Python 3.8+ Core runtime environment
pip Latest Package manager for dependencies
Internet Required API communication and authentication

Pro Tip: We recommend using Python 3.9+ for optimal performance and the latest language features.

Getting Started with FastPix

To get started with the FastPix Python SDK, ensure you have the following:

  • The FastPix APIs are authenticated using an Access Token and a Secret Key. You must generate these credentials to use the SDK.

  • Follow the steps in the Authentication with Access Tokens guide to obtain your credentials.

Environment Variables (Optional)

Configure your FastPix credentials using environment variables for enhanced security and convenience:

# Set your FastPix credentials
export FASTPIX_ACCESS_TOKEN="your_access_token_here"
export FASTPIX_SECRET_KEY="your_secret_key_here"

# Or add to your .env file
echo "FASTPIX_ACCESS_TOKEN=your_access_token_here" >> .env
echo "FASTPIX_SECRET_KEY=your_secret_key_here" >> .env

Security Note: Never commit your credentials to version control. Use environment variables or secure credential management systems.

Table of Contents

Setup

Installation

Install the FastPix Python SDK using pip:

pip install git+https://github.com/FastPix/fastpix-python

Or if you're using a virtual environment:

# Create virtual environment
python -m venv fastpix-env

# Activate virtual environment
# On Windows:
fastpix-env\Scripts\activate
# On macOS/Linux:
source fastpix-env/bin/activate

### Imports

Import the necessary modules for your FastPix integration:

```python
# Basic imports
from fastpix_python import Fastpix, models

# Specific API imports
from fastpix_python.manage_videos import ManageVideos
from fastpix_python.live_playback import LivePlayback
from fastpix_python.metrics import Metrics

# Error handling imports
from fastpix_python.errors import FastPixError, AuthenticationError

Initialization

Initialize the FastPix SDK with your credentials:

from fastpix_python import Fastpix, models

# Initialize with credentials
with Fastpix(
    security=models.Security(
        username="your-access-token",
        password="your-secret-key",
    ),
) as fastpix:
    # Your API calls here
    pass

Or using environment variables:

import os
from fastpix_python import Fastpix, models

# Initialize with environment variables
with Fastpix(
    security=models.Security(
        username=os.getenv("FASTPIX_ACCESS_TOKEN"),
        password=os.getenv("FASTPIX_SECRET_KEY"),
    ),
) as fastpix:
    # Your API calls here
    pass

Example Usage

Example

# Synchronous Example
from fastpix_python import Fastpix, models


with Fastpix(
    security=models.Security(
        username = "your-access-token",
        password = "secret-key",
    ),
) as fastpix:

    res = fastpix.input_video.create_media(inputs=[
        {
            "type": "video",
            "url": "https://static.fastpix.io/sample.mp4",
        },
    ], access_policy="public", metadata={
        "key1": "value1",
    }, subtitles={
        "language_name": "english",
        "metadata": {
            "key1": "value1",
        },
        "language_code": "en",
    }, mp4_support="capped_4k", source_access=True, optimize_audio=True, max_resolution="1080p", summary={
        "generate": True,
    }, chapters=True, named_entities=True)

    # Handle response
    print(res)

The same SDK client can also be used to make asynchronous requests by importing asyncio.

# Asynchronous Example
import asyncio
from fastpix_python import Fastpix, models

async def main():

    async with Fastpix(
        security=models.Security(
            username = "your-access-token",
            password = "secret-key",
        ),
    ) as fastpix:

        res = await fastpix.input_video.create_media_async(inputs=[
            {
                "type": "video",
                "url": "https://static.fastpix.io/sample.mp4",
            },
        ], access_policy="public", metadata={
            "key1": "value1",
        }, subtitles={
            "language_name": "english",
            "metadata": {
                "key1": "value1",
            },
            "language_code": "en",
        }, mp4_support="capped_4k", source_access=True, optimize_audio=True, max_resolution="1080p", summary={
            "generate": True,
        }, chapters=True, named_entities=True)

        # Handle response
        print(res)

asyncio.run(main())

Available Resources and Operations

single line description here

Media API

Upload, manage, and transform video content with comprehensive media management capabilities.

For detailed documentation, see FastPix Video on Demand Overview.

Input Video

Manage Videos

Playback

Playlist

Signing Keys

DRM Configurations

Live API

Stream, manage, and transform live video content with real-time broadcasting capabilities.

For detailed documentation, see FastPix Live Stream Overview.

Start Live Stream

Manage Live Stream

Live Playback

Simulcast Stream

Video Data API

Monitor video performance and quality with comprehensive analytics and real-time metrics.

For detailed documentation, see FastPix Video Data Overview.

Metrics

Views

Dimensions

In-Video AI Features

Enhance video content with AI-powered features including moderation, summarization, and intelligent categorization.

For detailed documentation, see Video Moderation Guide.

Error Handling

Handle and manage errors with comprehensive error handling capabilities and detailed error information for all API operations.

  • List Errors - Retrieve comprehensive error logs and diagnostics

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 fastpix_python import Fastpix, models
from fastpix_python.utils import BackoffStrategy, RetryConfig


with Fastpix(
    security=models.Security(
        username = "your-access-token",
        password = "secret-key",
    ),
) as fastpix:

    res = fastpix.input_video.create_media(inputs=[
        {
            "type": "video",
            "url": "https://static.fastpix.io/sample.mp4",
        },
    ], access_policy="public", metadata={
        "key1": "value1",
    }, subtitles={
        "language_name": "english",
        "metadata": {
            "key1": "value1",
        },
        "language_code": "en",
    }, mp4_support="capped_4k", source_access=True, optimize_audio=True, max_resolution="1080p", summary={
        "generate": True,
    }, chapters=True, named_entities=True,
        RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))

    # Handle response
    print(res)

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 fastpix_python import Fastpix, models
from fastpix_python.utils import BackoffStrategy, RetryConfig


with Fastpix(
    retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
    security=models.Security(
        username = "your-access-token",
        password = "secret-key",
    ),
) as fastpix:

    res = fastpix.input_video.create_media(inputs=[
        {
            "type": "video",
            "url": "https://static.fastpix.io/sample.mp4",
        },
    ], access_policy="public", metadata={
        "key1": "value1",
    }, subtitles={
        "language_name": "english",
        "metadata": {
            "key1": "value1",
        },
        "language_code": "en",
    }, mp4_support="capped_4k", source_access=True, optimize_audio=True, max_resolution="1080p", summary={
        "generate": True,
    }, chapters=True, named_entities=True)

    # Handle response
    print(res)

Error Handling

FastpixError 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 fastpix_python import Fastpix, errors, models


with Fastpix(
    security=models.Security(
        username = "your-access-token",
        password = "secret-key",
    ),
) as fastpix:
    res = None
    try:

        res = fastpix.input_video.create_media(inputs=[
            {
                "type": "video",
                "url": "https://static.fastpix.io/sample.mp4",
            },
        ], access_policy="public", metadata={
            "key1": "value1",
        }, subtitles={
            "language_name": "english",
            "metadata": {
                "key1": "value1",
            },
            "language_code": "en",
        }, mp4_support="capped_4k", source_access=True, optimize_audio=True, max_resolution="1080p", summary={
            "generate": True,
        }, chapters=True, named_entities=True)

        # Handle response
        print(res)


    except errors.FastpixError 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.BadRequestError):
            print(e.data.success)  # Optional[bool]
            print(e.data.error)  # Optional[models.BadRequestError]

Error Classes

Primary errors:

Less common errors (27)

Network errors:

Inherit from FastpixError:

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

Server Selection

Override Server URL Per-Client

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

from fastpix_python import Fastpix, models


with Fastpix(
    server_url="https://api.fastpix.io/v1/",
    security=models.Security(
        username = "your-access-token",
        password = "secret-key",
    ),
) as fastpix:

    res = fastpix.input_video.create_media(inputs=[
        {
            "type": "video",
            "url": "https://static.fastpix.io/sample.mp4",
        },
    ], access_policy="public", metadata={
        "key1": "value1",
    }, subtitles={
        "language_name": "english",
        "metadata": {
            "key1": "value1",
        },
        "language_code": "en",
    }, mp4_support="capped_4k", source_access=True, optimize_audio=True, max_resolution="1080p", summary={
        "generate": True,
    }, chapters=True, named_entities=True)

    # Handle response
    print(res)

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 fastpix_python import Fastpix
import httpx

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

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

from fastpix_python import Fastpix
from fastpix_python.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 = Fastpix(async_client=CustomClient(httpx.AsyncClient()))

Resource Management

The Fastpix 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 fastpix_python import Fastpix, models
def main():

    with Fastpix(
        security=models.Security(
            username = "your-access-token",
            password = "secret-key",
        ),
    ) as fastpix:
        # Rest of application here...


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

    async with Fastpix(
        security=models.Security(
            username = "your-access-token",
            password = "secret-key",
        ),
    ) as fastpix:
        # 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 fastpix_python import Fastpix
import logging

logging.basicConfig(level=logging.DEBUG)
s = Fastpix(debug_logger=logging.getLogger("fastpix_python"))

You can also enable a default debug logger by setting an environment variable FASTPIX_DEBUG to true.

Development

This SDK is automatically generated from our API specifications. Manual modifications to internal files will be overwritten during the next generation cycle. We welcome community contributions and feedback. Please submit pull requests or open issues with your suggestions and we'll consider them for future releases.

Detailed Usage

For a complete understanding of each API's functionality, including request and response details, parameter descriptions, and additional examples, please refer to the FastPix API Reference.

The API reference provides comprehensive documentation for all available endpoints and features, ensuring developers can integrate and utilize FastPix APIs efficiently.

About

Python SDK is designed for secure and efficient communication with the FastPix API.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •  

Languages