# Cancelling a Subscription

This section explains how to **cancel stream subscriptions** using the supported protocols: **WebSocket** and **gRPC**.

### WebSocket

To cancel a WebSocket subscription, call the `unsubscribe` RPC method and pass the `subscription_id` returned by the original `subscribe` call.

#### **Examples**

{% tabs %}
{% tab title="Gateway" %}
Unsubscribe call example for the Gateway in Python (version 3.7 or higher):

```python
import asyncio, ssl, json, websockets

async def main():
    auth_key = "YOUR_AUTHORIZATION_HEADER"
    
    async with websockets.connect(
        'ws://127.0.0.1:28333/ws',
        header=["Authorization:{}".format(auth_key)],            
        sslopt={"cert_reqs": ssl.CERT_NONE},        
        ) as websocket:
            subscribe_request = {
                "jsonrpc": "2.0",
                "id": 1,
                "method": "subscribe",
                "params": ["newTxs", {"include": ["tx_hash"]}]
            }
            await websocket.send(json.dumps(subscribe_request))
            response = await websocket.recv()
            subscription_id = json.loads(response)["result"]
    
            unsubscribe_request = {
                "jsonrpc": "2.0",
                "id": 2,
                "method": "unsubscribe",
                "params": [subscription_id]
            }
            await websocket.send(json.dumps(unsubscribe_request))
            response = await websocket.recv()
            print("Unsubscribed successfully.")
    
if __name__ == '__main__':
    asyncio.run(main())
```

{% endtab %}

{% tab title="Cloud-API (Enterprise)" %}
Unsubscribe call example for the Cloud-API in Python (version 3.7 or higher):

```python
import asyncio, ssl, json, websockets

async def main():
    auth_key = "YOUR_AUTHORIZATION_HEADER"
    
    async with websockets.connect(
        'wss://virginia.eth.blxrbdn.com/ws',
        header=["Authorization:{}".format(auth_key)],            
        sslopt={"cert_reqs": ssl.CERT_NONE},        
        ) as websocket:
            subscribe_request = {
                "jsonrpc": "2.0",
                "id": 1,
                "method": "subscribe",
                "params": ["newTxs", {"include": ["tx_hash"]}]
            }
            await websocket.send(json.dumps(subscribe_request))
            response = await websocket.recv()
            subscription_id = json.loads(response)["result"]
    
            unsubscribe_request = {
                "jsonrpc": "2.0",
                "id": 2,
                "method": "unsubscribe",
                "params": [subscription_id]
            }
            await websocket.send(json.dumps(unsubscribe_request))
            response = await websocket.recv()
    
            print("Unsubscribed successfully.")
    
if __name__ == '__main__':
    asyncio.run(main())
```

{% endtab %}

{% tab title="Cloud-API (non-Enterprise)" %}
Unsubscribe call example for the Cloud-API in Python (version 3.7 or higher):

```python
import asyncio, ssl, json, websockets

async def main():
    auth_key = "YOUR_AUTHORIZATION_HEADER"
    
    async with websockets.connect(
        'wss://api.blxrbdn.com/ws',
        header=["Authorization:{}".format(auth_key)],            
        sslopt={"cert_reqs": ssl.CERT_NONE},        
        ) as websocket:
            subscribe_request = {
                "jsonrpc": "2.0",
                "id": 1,
                "method": "subscribe",
                "params": ["newTxs", {"include": ["tx_hash"]}]
            }
            await websocket.send(json.dumps(subscribe_request))
            response = await websocket.recv()
            subscription_id = json.loads(response)["result"]
    
            unsubscribe_request = {
                "jsonrpc": "2.0",
                "id": 2,
                "method": "unsubscribe",
                "params": [subscription_id]
            }
            await websocket.send(json.dumps(unsubscribe_request))
            response = await websocket.recv()
    
            print("Unsubscribed successfully.")
    
if __name__ == '__main__':
    asyncio.run(main())
```

{% endtab %}
{% endtabs %}

### gRPC

To unsubscribe from a gRPC stream, create the subscription using a cancellable context (for example, via `context.WithTimeout()` or `context.WithCancel()`). Canceling the context terminates the stream and stops further notifications.

#### **Example**

{% tabs %}
{% tab title="Gateway-API" %}
Subscribing to Gateway Stream in Go using gRPC (ex: NewTxs stream):

```go
package main

import (
	"context"
	"fmt"
	"time"

	pb "github.com/bloXroute-Labs/gateway/v2/protobuf"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

type blxrCredentials struct {
	authorization string
}

func (bc blxrCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"authorization": bc.authorization,
	}, nil
}

func (bc blxrCredentials) RequireTransportSecurity() bool {
	return false
}

func main() {
	// gRPC server default values
	gatewayHostIP := "localhost"
	gatewayGRPCPort := 5001
	
	// this will use localhost CA to verify the certificate
	creds := credentials.NewClientTLSFromCert(nil, "")

	// Open gRPC connection to Gateway.
	conn, _ := grpc.Dial(
		fmt.Sprintf("%v:%v", gatewayHostIP, gatewayGRPCPort),
		grpc.WithTransportCredentials(creds),
		grpc.WithPerRPCCredentials(blxrCredentials{authorization: "<YOUR-AUTHORIZATION-HEADER>"}),
		// for the best networking performance between gateway and a client
		// we recommend to use following dial configuration:
		grpc.WithWriteBufferSize(0),
		grpc.WithInitialConnWindowSize(128*1024),
	)

	// Use the Gateway client connection interface.
	client := pb.NewGatewayClient(conn)

	// create context and defer cancel of context
	callContext, cancel := context.WithTimeout(context.Background(), 24*time.Hour)
	defer cancel()

	// Create a subscription using the stream-specific method and request.
	stream, _ := client.NewTxs(callContext, &pb.TxsRequest{Filters: "", Includes: ""})

	for {
		subscriptionNotification, err := stream.Recv()
		if err == nil {
			fmt.Println(subscriptionNotification) // or process it generally
		}
	}
}
```

{% endtab %}
{% endtabs %}
