Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions examples/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Copy this file to ".env" and fill in your credentials, then load it in your
# shell before running an example (e.g. `export $(grep -v '^#' .env | xargs)`).
#
# From your FastPix Dashboard (https://dashboard.fastpix.com):
# Access Token -> FASTPIX_USERNAME
# Secret Key -> FASTPIX_PASSWORD
FASTPIX_USERNAME=
FASTPIX_PASSWORD=

# From Dashboard > Webhooks (needed to verify webhook signatures).
FASTPIX_WEBHOOK_SECRET=

# Optional: an existing "Ready" media id, used by ai_features.rb.
# FASTPIX_MEDIA_ID=
6 changes: 6 additions & 0 deletions examples/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.env
rails-example/tmp/
rails-example/log/
rails-example/.bundle/
rails-example/vendor/
rails-example/Gemfile.lock
87 changes: 87 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# FastPix Ruby SDK examples

Small, runnable scripts that show how to use the SDK against the FastPix API,
plus a minimal Rails app that wires uploads and webhooks into HTTP endpoints.

## Setup

You'll need Ruby 3.2+ and a FastPix account.

1. Install the SDK (from RubyGems, or point Bundler at this repo while developing):

```bash
gem install fastpixapi
```

2. Set your credentials. Copy `.env.example` to `.env`, fill it in, and load it:

```bash
cp .env.example .env
# edit .env, then:
export $(grep -v '^#' .env | xargs)
```

`FASTPIX_USERNAME` is your Access Token and `FASTPIX_PASSWORD` is your Secret
Key, both from the [Dashboard](https://dashboard.fastpix.com). The examples
read them from the environment — nothing is hardcoded.

3. Run any example:

```bash
ruby examples/basic_usage.rb
```

## The examples

| File | What it does |
| --- | --- |
| `basic_usage.rb` | Initialise the SDK and read from a few endpoints. |
| `create_upload.rb` | Mint a signed direct-upload URL for a device upload. |
| `verify_webhook.rb` | Verify a webhook signature. Runs offline, no credentials. |
| `media_upload.rb` | Create a media from a URL, read it, delete it. |
| `live_streaming.rb` | Create a live stream, toggle it, delete it. |
| `playlist_management.rb` | Create a playlist, add a media, delete it. |
| `signing_keys.rb` | Create, read and delete a signing key. |
| `analytics.rb` | Read views, dimensions, metrics and errors. |
| `drm_configuration.rb` | List DRM configurations. |
| `ai_features.rb` | Enable summary, chapters and named entities on a media. |
| `configuration.rb` | SDK options: timeout, retries, custom server URL. |
| `rails-example/` | A Rails app exposing `/uploads` and `/webhooks`. |

A few examples need account features to be enabled (live streaming, DRM,
admin-level signing keys) or an existing ready media (`ai_features.rb`, via
`FASTPIX_MEDIA_ID`). When something isn't available they print why and exit
cleanly rather than failing hard.

## Uploading a file after you have a signed URL

`create_upload.rb` (and the Rails `/uploads` endpoint) hand you a signed URL.
The client uploads the file straight to that URL, so the bytes never touch your
server. Once it finishes, FastPix processes the video and sends the
`video.media.ready` webhook.

We keep this simple and PUT the whole file in one request — good enough for
small files. For larger ones you'll usually want a resumable upload (chunked,
with retries and progress); the same signed URL supports that too.

```bash
# Upload the file straight to the signed URL from create_upload.rb
curl -X PUT --upload-file video.mp4 \
-H "Content-Type: video/mp4" \
"$UPLOAD_URL"
```

Or from the browser, straight off a file input:

```js
const { url } = await (await fetch("/uploads", { method: "POST" })).json();
await fetch(url, {
method: "PUT",
headers: { "Content-Type": file.type || "application/octet-stream" },
body: file,
});
```

The examples mint uploads with `cors_origin: "*"` so the browser can PUT from
anywhere — lock that down before you ship. The docs go deeper, resumable
included: https://fastpix.com/docs/upload-videos/upload-videos-from-device
42 changes: 42 additions & 0 deletions examples/ai_features.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

# Turn on in-video AI features (summary, chapters, named entities) for a media.
# These need a media that is already "Ready", so set FASTPIX_MEDIA_ID to an
# existing ready media id before running.

require 'fastpixapi'
require 'json'

Models = ::FastpixClient::Models
Ops = Models::Operations

media_id = ENV['FASTPIX_MEDIA_ID']
if media_id.nil? || media_id.empty?
abort 'Set FASTPIX_MEDIA_ID to a ready media id first (see the comment at the top).'
end

sdk = ::FastpixClient::Fastpixapi.new(
security: Models::Components::Security.new(
username: ENV.fetch('FASTPIX_USERNAME'),
password: ENV.fetch('FASTPIX_PASSWORD')
)
)

summary = sdk.in_video_ai_features.update_media_summary(
media_id: media_id,
body: Ops::UpdateMediaSummaryRequestBody.new(generate: true)
)
puts "update_media_summary -> HTTP #{summary.status_code}"

chapters = sdk.in_video_ai_features.update_media_chapters(
media_id: media_id,
body: Ops::UpdateMediaChaptersRequestBody.new(chapters: true)
)
puts "update_media_chapters -> HTTP #{chapters.status_code}"

entities = sdk.in_video_ai_features.update_media_named_entities(
media_id: media_id,
body: Ops::UpdateMediaNamedEntitiesRequestBody.new(named_entities: true)
)
puts "update_media_named_entities -> HTTP #{entities.status_code}"
43 changes: 43 additions & 0 deletions examples/analytics.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

# Read-only tour of the analytics endpoints: views, dimensions, metrics, errors.
# All are scoped to a time window; here we use the last 24 hours.

require 'fastpixapi'
require 'json'

Models = ::FastpixClient::Models
Ops = Models::Operations

sdk = ::FastpixClient::Fastpixapi.new(
security: Models::Components::Security.new(
username: ENV.fetch('FASTPIX_USERNAME'),
password: ENV.fetch('FASTPIX_PASSWORD')
)
)

def rows(res)
data = JSON.parse(res.raw_response.body)['data']
data.is_a?(Array) ? data.length : 'n/a'
rescue StandardError
'n/a'
end

views = sdk.views.list_video_views(
request: Ops::ListVideoViewsRequest.new(timespan: Ops::ListVideoViewsTimespan::TWENTY_FOURHOURS)
)
puts "list_video_views -> HTTP #{views.status_code}, #{rows(views)} row(s)"

dims = sdk.dimensions.list_dimensions
puts "list_dimensions -> HTTP #{dims.status_code}, #{rows(dims)} row(s)"

overall = sdk.metrics.list_overall_values(
metric_id: Ops::ListOverallValuesMetricId::QUALITY_OF_EXPERIENCE_SCORE,
measurement: 'avg',
timespan: Ops::ListOverallValuesTimespan::TWENTY_FOURHOURS
)
puts "list_overall_values -> HTTP #{overall.status_code}"

errors = sdk.errors.list_errors(timespan: Ops::ListErrorsTimespan::TWENTY_FOURHOURS)
puts "list_errors -> HTTP #{errors.status_code}, #{rows(errors)} row(s)"
36 changes: 36 additions & 0 deletions examples/basic_usage.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

# Connectivity check: initialise the SDK and read from a few endpoints.

require 'fastpixapi'
require 'json'

Models = ::FastpixClient::Models

sdk = ::FastpixClient::Fastpixapi.new(
security: Models::Components::Security.new(
username: ENV.fetch('FASTPIX_USERNAME'),
password: ENV.fetch('FASTPIX_PASSWORD')
)
)

def count(res)
data = JSON.parse(res.raw_response.body)['data']
data.is_a?(Array) ? data.length : 'n/a'
rescue StandardError
'n/a'
end

media = sdk.manage_videos.list_media(limit: 5)
puts "list_media -> HTTP #{media.status_code}, #{count(media)} item(s)"

streams = sdk.manage_live_stream.get_all_streams(limit: 5)
puts "get_all_streams -> HTTP #{streams.status_code}, #{count(streams)} item(s)"

views = sdk.views.list_video_views(
request: Models::Operations::ListVideoViewsRequest.new(
timespan: Models::Operations::ListVideoViewsTimespan::TWENTY_FOURHOURS
)
)
puts "list_video_views -> HTTP #{views.status_code}, #{count(views)} item(s)"
36 changes: 36 additions & 0 deletions examples/configuration.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

# Show the SDK constructor options: request timeout, retries, and a custom
# server URL. Each is optional; the defaults are fine for most apps.

require 'fastpixapi'

Models = ::FastpixClient::Models
Utils = ::FastpixClient::Utils

security = Models::Components::Security.new(
username: ENV.fetch('FASTPIX_USERNAME'),
password: ENV.fetch('FASTPIX_PASSWORD')
)

# Retries with exponential backoff (all fields optional).
retry_config = Utils::RetryConfig.new(
backoff: Utils::BackoffStrategy.new(
initial_interval: 500, # ms
max_interval: 10_000, # ms
exponent: 1.5,
max_elapsed_time: 30_000 # ms
),
retry_connection_errors: true
)

sdk = ::FastpixClient::Fastpixapi.new(
security: security,
timeout_ms: 20_000, # per-request timeout
retry_config: retry_config
# server_url: 'https://api.fastpix.com/v1/' # override the API base URL if needed
)

res = sdk.manage_videos.list_media(limit: 1)
puts "Configured client works -> HTTP #{res.status_code}"
36 changes: 36 additions & 0 deletions examples/create_upload.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

# Mint a signed direct-upload URL. The client then PUTs the file straight to
# that URL, so the bytes never touch your server. See examples/README.md for
# setup and how to upload the file once you have the URL.

require 'fastpixapi'

Models = ::FastpixClient::Models

sdk = ::FastpixClient::Fastpixapi.new(
security: Models::Components::Security.new(
username: ENV.fetch('FASTPIX_USERNAME'),
password: ENV.fetch('FASTPIX_PASSWORD')
)
)

req = Models::Operations::DirectUploadVideoMediaRequest.new(
cors_origin: '*', # tighten this to your own origin before you ship
push_media_settings: Models::Operations::PushMediaSettings.new(
metadata: { 'source' => 'create_upload_example' }
)
)

res = sdk.input_video.direct_upload_video_media(request: req)
data = res.object&.data

puts "Upload ID: #{data&.upload_id}"
puts "Timeout: #{data&.timeout}s"
puts
puts 'PUT your file to this signed URL to upload it:'
puts data&.url
puts
puts 'e.g. curl -X PUT --upload-file video.mp4 \\'
puts ' -H "Content-Type: video/mp4" "<the url above>"'
41 changes: 41 additions & 0 deletions examples/drm_configuration.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

# Read-only: list your DRM configurations and fetch one by id.
# DRM configs are created in the Dashboard; the SDK reads them.

require 'fastpixapi'
require 'json'

Models = ::FastpixClient::Models

sdk = ::FastpixClient::Fastpixapi.new(
security: Models::Components::Security.new(
username: ENV.fetch('FASTPIX_USERNAME'),
password: ENV.fetch('FASTPIX_PASSWORD')
)
)

def body(res)
JSON.parse(res.raw_response.body)
rescue StandardError
{}
end

# The list endpoint returns 400 when the workspace has no DRM configuration yet.
begin
list = sdk.drm_configurations.get_drm_configuration(limit: 10)
rescue FastpixClient::Models::Errors::APIError => e
warn "get_drm_configuration: #{JSON.parse(e.body).dig('error', 'message') rescue e.body}"
warn 'Create a DRM configuration in the Dashboard, then rerun.'
exit 0
end
configs = body(list)['data'] || []
puts "get_drm_configuration -> HTTP #{list.status_code}, #{configs.length} config(s)"

if (drm_id = configs.dig(0, 'id'))
one = sdk.drm_configurations.get_drm_configuration_by_id(drm_configuration_id: drm_id)
puts "get_drm_configuration_by_id -> HTTP #{one.status_code}, id #{drm_id}"
else
puts 'get_drm_configuration_by_id -> skipped (no DRM configs; create one in the Dashboard)'
end
28 changes: 28 additions & 0 deletions examples/error_handling.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

# How to handle API errors. Every failed request raises
# FastpixClient::Models::Errors::APIError, which carries the HTTP status and
# the raw response body so you can read the server's error details.

require 'fastpixapi'
require 'json'
require 'securerandom'

Models = ::FastpixClient::Models

sdk = ::FastpixClient::Fastpixapi.new(
security: Models::Components::Security.new(
username: ENV.fetch('FASTPIX_USERNAME'),
password: ENV.fetch('FASTPIX_PASSWORD')
)
)

begin
# A media id that doesn't exist -> the API returns an error.
sdk.manage_videos.get_media(media_id: SecureRandom.uuid)
rescue FastpixClient::Models::Errors::APIError => e
puts "Caught APIError: HTTP #{e.status_code}"
error = (JSON.parse(e.body)['error'] rescue nil)
puts " message: #{error&.fetch('message', nil) || e.body}"
end
Loading