> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pipecat.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# FastAPIWebsocketTransport

> WebSocket transport implementation for FastAPI web applications with telephony integration

## Overview

`FastAPIWebsocketTransport` provides WebSocket support for FastAPI web applications, enabling real-time audio communication over WebSocket connections. It's primarily designed for telephony integrations with providers like Twilio, Telnyx, and Plivo, supporting bidirectional audio streams with configurable serializers and voice activity detection.

<Warning>
  FastAPIWebsocketTransport is best suited for telephony applications and server-side WebSocket integrations.

  For general client/server applications, we recommend using WebRTC-based transports for more robust network and media handling.
</Warning>

<CardGroup cols={2}>
  <Card title="FastAPI WebSocket API Reference" icon="code" href="https://reference-server.pipecat.ai/en/latest/api/pipecat.transports.websocket.fastapi.html">
    Pipecat's API methods for FastAPI WebSocket integration
  </Card>

  <Card title="Example Implementation" icon="play" href="https://github.com/pipecat-ai/pipecat-examples/tree/main/twilio-chatbot">
    Complete Twilio telephony integration example
  </Card>

  <Card title="FastAPI Documentation" icon="book" href="https://fastapi.tiangolo.com/advanced/websockets/">
    Official FastAPI WebSocket documentation
  </Card>

  <Card title="Telephony Serializers" icon="settings" href="/api-reference/server/services/serializers/introduction">
    Learn about supported FrameSerializers for telephony providers
  </Card>
</CardGroup>

## Installation

To use FastAPIWebsocketTransport, install the required dependencies:

```bash theme={null}
uv add "pipecat-ai[websocket]"
```

## Prerequisites

### FastAPI Application Setup

Before using FastAPIWebsocketTransport, you need:

1. **FastAPI Application**: Set up a FastAPI web application
2. **WebSocket Endpoint**: Configure WebSocket routes for real-time communication
3. **Telephony Provider**: Set up integration with Twilio, Telnyx, or Plivo
4. **Frame Serializers**: Configure appropriate serializers for your telephony provider

### Configuration Options

* **Serializer Selection**: Choose frame serializer based on telephony provider
* **Audio Parameters**: Configure sample rates and audio formats
* **VAD Integration**: Set up voice activity detection for optimal performance
* **Connection Management**: Handle WebSocket lifecycle and reconnections

### Key Features

* **Telephony Integration**: Optimized for Twilio, Telnyx, and Plivo WebSocket streams
* **Frame Serialization**: Built-in support for telephony provider audio formats
* **FastAPI Integration**: Seamless WebSocket handling within FastAPI applications
* **Bidirectional Audio**: Real-time audio streaming in both directions

## Configuration

### FastAPIWebsocketTransport

<ParamField path="websocket" type="WebSocket" required>
  The FastAPI WebSocket connection instance.
</ParamField>

<ParamField path="params" type="FastAPIWebsocketParams" required>
  Transport configuration parameters.
</ParamField>

<ParamField path="input_name" type="str" default="None">
  Optional name for the input transport processor.
</ParamField>

<ParamField path="output_name" type="str" default="None">
  Optional name for the output transport processor.
</ParamField>

### FastAPIWebsocketParams

Inherits from `TransportParams` with additional WebSocket-specific parameters.

<ParamField path="add_wav_header" type="bool" default="False">
  Whether to add WAV headers to outgoing audio frames.
</ParamField>

<ParamField path="serializer" type="FrameSerializer" default="None">
  Frame serializer for encoding/decoding WebSocket messages. Use a telephony
  serializer (e.g., `TwilioFrameSerializer`, `TelnyxFrameSerializer`) for
  provider-specific audio formats.
</ParamField>

<ParamField path="session_timeout" type="int" default="None">
  Session timeout in seconds. When set, triggers `on_session_timeout` if the
  session exceeds this duration. `None` disables the timeout.
</ParamField>

<ParamField path="fixed_audio_packet_size" type="int" default="None">
  Optional fixed-size packetization for raw PCM audio payloads. Useful when the
  remote WebSocket media endpoint requires strict audio framing (e.g., 640 bytes
  for 20ms at 16kHz PCM16 mono).
</ParamField>

## Usage

FastAPIWebsocketTransport integrates with your FastAPI application to handle telephony WebSocket connections. It works with telephony frame serializers to process audio streams from phone calls.

See the [complete example](https://github.com/pipecat-ai/pipecat-examples/tree/main/twilio-chatbot) for a full implementation including:

* FastAPI WebSocket endpoint configuration
* Telephony provider integration setup
* Frame serializer configuration
* Audio processing pipeline integration

## Event Handlers

FastAPIWebsocketTransport provides event handlers for client connection lifecycle and session management. Register handlers using the `@event_handler` decorator on the transport instance.

### Events Summary

| Event                    | Description                   |
| ------------------------ | ----------------------------- |
| `on_client_connected`    | Client WebSocket connected    |
| `on_client_disconnected` | Client WebSocket disconnected |
| `on_session_timeout`     | Session timed out             |

### Connection Lifecycle

#### on\_client\_connected

Fired when a client successfully connects to the WebSocket.

```python theme={null}
@transport.event_handler("on_client_connected")
async def on_client_connected(transport, websocket):
    print("Client connected")
```

**Parameters:**

| Parameter   | Type                        | Description                             |
| ----------- | --------------------------- | --------------------------------------- |
| `transport` | `FastAPIWebsocketTransport` | The transport instance                  |
| `websocket` | `WebSocket`                 | The FastAPI WebSocket connection object |

#### on\_client\_disconnected

Fired when a client disconnects from the WebSocket.

```python theme={null}
@transport.event_handler("on_client_disconnected")
async def on_client_disconnected(transport, websocket):
    print("Client disconnected")
```

**Parameters:**

| Parameter   | Type                        | Description                             |
| ----------- | --------------------------- | --------------------------------------- |
| `transport` | `FastAPIWebsocketTransport` | The transport instance                  |
| `websocket` | `WebSocket`                 | The FastAPI WebSocket connection object |

#### on\_session\_timeout

Fired when a session exceeds the configured `session_timeout` duration. Only fires if `session_timeout` is set in the params.

```python theme={null}
@transport.event_handler("on_session_timeout")
async def on_session_timeout(transport, websocket):
    print("Session timed out")
```

**Parameters:**

| Parameter   | Type                        | Description                             |
| ----------- | --------------------------- | --------------------------------------- |
| `transport` | `FastAPIWebsocketTransport` | The transport instance                  |
| `websocket` | `WebSocket`                 | The FastAPI WebSocket connection object |

## Additional Resources

* [Events Overview](/api-reference/server/events/overview) - Overview of all events in Pipecat
* [Serializers](/api-reference/server/services/serializers/introduction) - Frame serializers for telephony providers
