Skip to main content

SocketAPI is a lightweight Python framework for real-time WebSocket APIs, using a single multiplexed connection with endpoint-like actions and channel subscriptions.

Project description

socketapi

GitHub License Tests Codecov PyPI - Python Version PyPI - Version Code style: black Linting: Ruff uv Starlette Pydantic Pytest Material for MkDocs

The main goal of SocketAPI is to provide an easy-to-use and flexible framework for building WebSocket APIs using Python. It leverages the power of Starlette for handling WebSocket connections and Pydantic for data validation and serialization. It uses a single multiplexed WebSocket connection, allowing clients to exchange different types of information through endpoint-like actions and channel subscriptions, defined similarly to routes in FastAPI. The framework is inspired by both FastAPI and Phoenix LiveView, combining familiar declarative endpoints with real-time, channel-oriented communication.

Installation

You can install SocketAPI using pip:

pip install socketapi

Simple example

Server

from socketapi import SocketAPI

app = SocketAPI()

# Define "add_numbers" action - endpoint for performing calculations
@app.action("add_numbers")
async def add_numbers(a: int, b: int) -> int:
    return a + b

# Define "chat" channel - subscription for receiving messages
@app.channel("chat")
async def chat_channel(message: str = "Welcome"):
    return {"message": message}

# Action that sends a message to all "chat" channel subscribers
@app.action("send_message")
async def send_message(message: str):
    await chat_channel(message=message)

Run the server with any ASGI server (e.g., Uvicorn):

uvicorn main:app --reload

Client Usage

Connect to the WebSocket endpoint at ws://localhost:8000/ and exchange JSON messages.

Calling an action (request-response pattern)

Send:

{"type": "action", "channel": "add_numbers", "data": {"a": 5, "b": 3}}

Receive:

{"type": "action", "channel": "add_numbers", "status": "completed", "data": 8}

Subscribing to a channel (pub/sub pattern)

Send:

{"type": "subscribe", "channel": "chat"}

Receive confirmation:

{"type": "subscribed", "channel": "chat"}

Broadcasting to channel subscribers

Send:

{"type": "action", "channel": "send_message", "data": {"message": "Hello everyone!"}}

Receive confirmation:

{"type": "action", "channel": "send_message", "status": "completed"}

All subscribers receive:

{"type": "data", "channel": "chat", "data": {"message": "Hello everyone!"}}

How it works:

  • Actions (@app.action) - endpoint-like, request-response pattern. Client sends a request and receives a response.
  • Channels (@app.channel) - pub/sub pattern. Client subscribes to a channel and automatically receives all data emitted to that channel.
  • Single WebSocket - all operations (actions, channels) work through a single WebSocket connection multiplexed via the channel field.

Documentation

The full documentation is available at spaceshaman.github.io/socketapi/

Features and Roadmap

  • Define actions with request-response pattern
  • Define channels with pub/sub pattern
  • Single multiplexed WebSocket connection
  • Pydantic models for data validation
  • Error handling and validation
  • Dependency injection system (like FastAPI)
  • Router class for splitting API into multiple files similar to FastAPI
  • Broadcasting messages from outside the server context by calling channel-decorated functions
  • Error reporting inside decorated handlers with automatic error messages sent to client

Changelog

Changes for each release are thoroughly documented in release notes

Contributing

Contributions are welcome! Feel free to open an issue or submit a pull request. I would like to keep the library to be safe as possible, so i would appreciate if you cover any new feature with tests to maintain 100% coverage.

Install in a development environment

  1. First, clone the repository:

    git clone git@github.com:SpaceShaman/socketapi.git
    
  2. Install uv if you don't have it:

    curl -LsSf https://astral.sh/uv/install.sh | sh
    
  3. Create a virtual environment and install the dependencies:

    cd socketapi
    uv sync
    

Run tests

You can run the tests with the following command:

uv run pytest

You can also run the tests with coverage:

uv run pytest --cov=socketapi

License

This project is licensed under the terms of the MIT license

Project details


Download files

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

Source Distribution

socketapi-0.1.1.tar.gz (6.9 kB view details)

Uploaded Source

Built Distribution

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

socketapi-0.1.1-py3-none-any.whl (9.4 kB view details)

Uploaded Python 3

File details

Details for the file socketapi-0.1.1.tar.gz.

File metadata

  • Download URL: socketapi-0.1.1.tar.gz
  • Upload date:
  • Size: 6.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.17 {"installer":{"name":"uv","version":"0.9.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for socketapi-0.1.1.tar.gz
Algorithm Hash digest
SHA256 ec3a1b44c1f1c9fd6c03ca86d55fa20427000f92bcecec0ae5892d3f13d32361
MD5 d04559f793fa8e0e1118ad18d9c7e6f8
BLAKE2b-256 f0db4978fe06b96d8413afcd6c0e3cddd340eb55f93b3dbdd8426e9c228536e4

See more details on using hashes here.

File details

Details for the file socketapi-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: socketapi-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 9.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.9.17 {"installer":{"name":"uv","version":"0.9.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for socketapi-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 412bfffaa14081c103e08d55cbe17a84d0f017f7976dc5231c99340eb8983233
MD5 47d4378600656edb9e4be11731f6e616
BLAKE2b-256 db7fd0198511486976f164f35c8ac82cd3a1d8b26da413468f9b13cc4911af8f

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