Skip to main content

interactive-video-labs-fastapi

Interactive Video Labs Logo

PyPI Version License PyPI Downloads

FastAPI adapter for interactive-video-labs-core.

This package exposes HTTP endpoints for saving interactive-video decisions, restoring session state, and validating node transitions. It uses SQLAlchemy 2.x and request-scoped async database sessions.

The core decision ledger is designed to complement @interactive-video-labs/core, the framework-agnostic TypeScript player used by interactive video applications.

The core 0.3.0 live protocol is framework-agnostic. The wrapper does not add HTTP or WebSocket routing for room synchronization; applications can compose the core live event models and helpers with their own FastAPI WebSocket handlers.


Features

  • FastAPI application factory: Create an app with a configurable async database URL.
  • Decision API: Persist viewer choices through the core session repository.
  • Session resume API: Reconstruct the latest node and playback position.
  • Transition validation: Check whether a choice is allowed for the current node.
  • Typed request models: Validate transition requests with Pydantic.
  • Async SQLAlchemy storage: Use request-scoped async sessions and core SQLAlchemy models.
  • Automatic startup setup: Create the core database tables in the application lifespan.
  • Framework composition: Keep decision logic and persistence in the core package while the adapter handles HTTP concerns.
  • Core 0.3 live compatibility: Use the core protocol models and tally helpers alongside custom FastAPI WebSocket endpoints.

Requirements

  • Python 3.10 or newer
  • FastAPI 0.115 or newer
  • Pydantic 2.x
  • SQLAlchemy 2.x
  • interactive-video-labs-core 0.3.0 or newer

Installation

Poetry

poetry add interactive-video-labs-fastapi

pip

pip install interactive-video-labs-fastapi

Quick Start

1. Create the FastAPI app

from interactive_video_labs_fastapi import create_app

app = create_app(
    "sqlite+aiosqlite:///./interactive_video.db",
)

The default database URL is sqlite+aiosqlite:///./interactive_video.db.

2. Run the server

uvicorn interactive_video_labs_fastapi.main:app --reload

The application creates the core ORM tables during startup and closes the database engine during shutdown.

3. Save a decision

curl -X POST http://127.0.0.1:8000/decisions \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user-123",
    "session_id": "session-456",
    "video_id": "video-789",
    "node_id": "question-1",
    "choice_id": "answer-b",
    "timestamp": 12.5,
    "metadata": {"source": "web"}
  }'

Response:

{
  "status": "saved"
}

4. Resume a session

curl http://127.0.0.1:8000/sessions/user-123/session-456

Example response:

{
  "user_id": "user-123",
  "session_id": "session-456",
  "video_id": "video-789",
  "last_node_id": "question-1",
  "last_timestamp": 12.5,
  "decision_history": [
    {
      "user_id": "user-123",
      "session_id": "session-456",
      "video_id": "video-789",
      "node_id": "question-1",
      "choice_id": "answer-b",
      "timestamp": 12.5,
      "metadata": {
        "source": "web"
      }
    }
  ],
  "updated_at": "2026-11-21T18:13:43Z"
}

When no decision exists for the user and session, the endpoint returns null.


API Endpoints

GET /health

Returns service availability:

{
  "status": "ok"
}

POST /decisions

Persists a decision through SQLAlchemySessionRepository.

{
  "user_id": "user-123",
  "session_id": "session-456",
  "video_id": "video-789",
  "node_id": "question-1",
  "choice_id": "answer-b",
  "timestamp": 12.5,
  "metadata": {
    "source": "web"
  }
}

Returns HTTP 201 with:

{
  "status": "saved"
}

GET /sessions/{user_id}/{session_id}

Reconstructs and returns the latest state for a viewing session.

The response includes the latest video, node, playback timestamp, chronological decision history, and latest update time.

POST /transitions/validate

Checks whether a choice is allowed for the current node:

{
  "current_node": "question-1",
  "choice_id": "answer-b",
  "allowed_choices": ["answer-a", "answer-b"]
}

Valid response:

{
  "valid": true
}

Invalid response:

{
  "valid": false
}

Live Session Protocol

Core 0.3.0 provides framework-agnostic live session events and room aggregation helpers. FastAPI applications can validate and dispatch those events in custom WebSocket handlers:

from pydantic import TypeAdapter
from interactive_video_backend_core.live import (
    DecisionSubmittedEvent,
    LiveSessionEvent,
    handle_decision_submitted,
)

event = TypeAdapter(LiveSessionEvent).validate_json(message)

if isinstance(event, DecisionSubmittedEvent):
    updates = await handle_decision_submitted(
        event,
        repository,
        previous_decisions=room_decisions,
    )
    await broadcast(updates.poll_tally.model_dump(mode="json"))
    await broadcast(updates.analytics_updated.model_dump(mode="json"))

The protocol uses version 1 and the following discriminator types:

Event type Purpose
room:state Reconnect snapshot
playback:sync Shared playback position
cue:triggered Cue activation
node:entered Node activation
decision:submitted Viewer choice submission
poll:tally Node choice totals
analytics:updated Video decision totals
presence:update Viewer join or leave state

The core live module does not manage WebSocket connections or room ledgers. The host application must handle authentication, room membership, participant state, ledger loading, and broadcasting. Supply previous_decisions without the incoming submitted decision.


Custom Application Setup

Use the application factory in a custom ASGI entry point:

from interactive_video_labs_fastapi import create_app

app = create_app(
    "postgresql+asyncpg://user:password@localhost/interactive_video"
)

For testing, create an app with an in-memory SQLite database:

from fastapi.testclient import TestClient

from interactive_video_labs_fastapi import create_app

app = create_app("sqlite+aiosqlite:///:memory:")

with TestClient(app) as client:
    response = client.get("/health")
    assert response.status_code == 200

Database table creation is designed for this adapter's simple default setup. Use your application's migration tooling for production database deployments.


Request and Response Models

TransitionValidationRequest

Field Type Description
current_node str Node currently being viewed
choice_id str Choice submitted by the viewer
allowed_choices list[str] Choices permitted for the current node

TransitionValidationResponse

Field Type Description
valid bool Whether the submitted choice is valid

Decision submissions and session resume responses use the Pydantic models supplied by interactive-video-labs-core.


Development

Clone the repository and install the development dependencies:

git clone https://github.com/interactive-video-labs/interactive-video-labs-fastapi.git
cd interactive-video-labs-fastapi
poetry install

Start the development server:

poetry run uvicorn interactive_video_labs_fastapi.main:app --reload

Run the test suite:

poetry run pytest

For setup details and project conventions, see DEVELOPER.md.


Project Structure

interactive-video-labs-fastapi/
├── interactive_video_labs_fastapi/
│   ├── __init__.py
│   ├── app.py
│   ├── dependencies.py
│   ├── main.py
│   ├── models.py
│   └── routes.py
├── tests/
│   └── test_api.py
├── pyproject.toml
└── README.md

Contributing

Contributions are welcome. Please review DEVELOPER.md and CODE_OF_CONDUCT.md before submitting an issue or pull request.


License

This project is licensed under the MIT License.

Metadata

Release files for interactive-video-labs-fastapi 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for interactive-video-labs-fastapi 0.3.0
File Size Uploaded Provenance Actions
interactive_video_labs_fastapi-0.3.0.tar.gz 5.9 kB With provenance Details for interactive_video_labs_fastapi-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for interactive-video-labs-fastapi 0.3.0
File Interpreter ABI Platform Actions
interactive_video_labs_fastapi-0.3.0-py3-none-any.whl Python 3 none any Details for interactive_video_labs_fastapi-0.3.0-py3-none-any.whl

Total release size: 13.9 kB

Release files / interactive_video_labs_fastapi-0.3.0.tar.gz

Download URL interactive_video_labs_fastapi-0.3.0.tar.gz
Size 5.9 kB
Tags Source
SHA-256 checksum
How to use checksums
fa97f2829f822ab50888e1608db6df88394a9e781d60a7d8d79364c171032b8a
BLAKE2b-256 checksum
How to use checksums
3a5c3447cfc431050da65622fa01cfcde8f4054ae630544bd9eeba4e514a4806
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Release files / interactive_video_labs_fastapi-0.3.0-py3-none-any.whl

Download URL interactive_video_labs_fastapi-0.3.0-py3-none-any.whl
Size 8.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
88df7074c4560ef2a902367912ca10626ecf30450785d4552f06f153fb907624
BLAKE2b-256 checksum
How to use checksums
0c98781961720984aa9507323f5f8f89f8ef1c7d65bd38d56b7b5e818962a7e0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Security for interactive-video-labs-fastapi 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for interactive_video_labs_fastapi-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page