Deletes a subscription.

## Explore further


For detailed documentation that includes this code sample, see the following:

- [Delete subscriptions](https://docs.cloud.google.com/pubsub/docs/delete-subscriptions.md.txt)

## Code sample

### C++


Before trying this sample, follow the C++ setup instructions in the
[Pub/Sub quickstart using
client libraries](https://docs.cloud.google.com/pubsub/docs/quickstart-client-libraries).


For more information, see the
[Pub/Sub C++ API
reference documentation](https://googleapis.dev/cpp/google-cloud-pubsub/latest/).


To authenticate to Pub/Sub, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```c++
namespace pubsub_admin = ::google::cloud::pubsub_admin;
namespace pubsub = ::google::cloud::pubsub;
[](pubsub_admin::SubscriptionAdminClient client,
   std::string const& project_id, std::string const& subscription_id) {
  auto status = client.DeleteSubscription(
      pubsub::Subscription(project_id, subscription_id).FullName());
  // Note that kNotFound is a possible result when the library retries.
  if (status.code() == google::cloud::StatusCode::kNotFound) {
    std::cout << "The subscription was not found\n";
    return;
  }
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "The subscription was successfully deleted\n";
```

### C#


Before trying this sample, follow the C# setup instructions in the
[Pub/Sub quickstart using
client libraries](https://docs.cloud.google.com/pubsub/docs/quickstart-client-libraries).


For more information, see the
[Pub/Sub C# API
reference documentation](https://cloud.google.com/dotnet/docs/reference/Google.Cloud.PubSub.V1/latest).


To authenticate to Pub/Sub, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```c#

using Google.Cloud.PubSub.V1;

public class DeleteSubscriptionSample
{
    public void DeleteSubscription(string projectId, string subscriptionId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        subscriber.DeleteSubscription(subscriptionName);
    }
}
```

### Go


Before trying this sample, follow the Go setup instructions in the
[Pub/Sub quickstart using
client libraries](https://docs.cloud.google.com/pubsub/docs/quickstart-client-libraries).


For more information, see the
[Pub/Sub Go API
reference documentation](https://godoc.org/cloud.google.com/go/pubsub).


To authenticate to Pub/Sub, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```go
import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub/v2"
	"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
)

func delete(w io.Writer, projectID, subID string) error {
	// projectID := "my-project-id"
	// subID := "my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	req := &pubsubpb.DeleteSubscriptionRequest{
		Subscription: fmt.Sprintf("projects/%s/subscriptions/%s", projectID, subID),
	}
	if err := client.SubscriptionAdminClient.DeleteSubscription(ctx, req); err != nil {
		return fmt.Errorf("Delete: %w", err)
	}
	fmt.Fprintf(w, "Subscription %q deleted.", subID)
	return nil
}
```

### Java


Before trying this sample, follow the Java setup instructions in the
[Pub/Sub quickstart using
client libraries](https://docs.cloud.google.com/pubsub/docs/quickstart-client-libraries).


For more information, see the
[Pub/Sub Java API
reference documentation](https://docs.cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/overview).


To authenticate to Pub/Sub, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```java
import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.ProjectSubscriptionName;

public class DeleteSubscription {

  public static void deleteSubscription(String projectId, String subId) throws Exception {
    try (SubscriptionAdminClient client = SubscriptionAdminClient.create()) {
      String subscription = ProjectSubscriptionName.of(projectId, subId).toString();
      client.deleteSubscription(subscription);
      System.out.println("Deleted subscription: " + subscription);
    }
  }
}
```

### Kotlin

```kotlin
import com.google.api.gax.rpc.ApiException
import com.google.api.gax.rpc.NotFoundException
import com.google.cloud.pubsub.v1.SubscriptionAdminClient
import com.google.pubsub.v1.SubscriptionName
import java.io.IOException

/**
 * Deletes an existing Google Cloud Pub/Sub subscription.
 *
 * @param projectId Google Cloud project identifier (for example, "example-project-id").
 * @param subscriptionId Pub/Sub subscription identifier to delete (for example, "example-subscription-id").
 */
fun deleteSubscription(projectId: String, subscriptionId: String) {
  val subscriptionName = SubscriptionName.of(projectId, subscriptionId)

  try {
    SubscriptionAdminClient.create().use { subscriptionAdminClient ->
      subscriptionAdminClient.deleteSubscription(subscriptionName)

      println("Resource ID: $subscriptionName")
      println("Deleted: true")
      println("Subscription ID: $subscriptionId")
    }
  } catch (err: NotFoundException) {
    System.err.println(
      "error: subscription '$subscriptionId' not found in project '$projectId': ${err.message}"
    )
  } catch (err: ApiException) {
    System.err.println(
      "error: failed to delete subscription '$subscriptionId' in project '$projectId': ${err.message}"
    )
  } catch (err: IOException) {
    System.err.println(
      "error: failed to initialize SubscriptionAdminClient for subscription '$subscriptionId' in project '$projectId': ${err.message}"
    )
  }
}
```

### Node.js


Before trying this sample, follow the Node.js setup instructions in the
[Pub/Sub quickstart using
client libraries](https://docs.cloud.google.com/pubsub/docs/quickstart-client-libraries).


For more information, see the
[Pub/Sub Node.js API
reference documentation](https://googleapis.dev/nodejs/pubsub/latest).


To authenticate to Pub/Sub, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```javascript
'use strict';

const {SubscriberClient} = require('@google-cloud/pubsub-api');
const {status} = require('@grpc/grpc-js');

const client = new SubscriberClient();

/**
 * Use the deleteSubscription method
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id')
 * @param {string} subId - ID of the Sub (for example, 'example-sub-id')
 */
async function deleteSubscription(projectId, subId) {
  try {
    const subscription = client.subscriptionPath(projectId, subId);
    const request = {
      subscription,
    };

    await client.deleteSubscription(request);
    console.log(`Subscription deleted: ${subscription}`);
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error('Subscription not found.');
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error('Permission denied deleting subscription.');
    } else {
      console.error(`Failed to delete subscription: ${err.message}`);
    }
  }
}

module.exports = { deleteSubscription };
```

### PHP


Before trying this sample, follow the PHP setup instructions in the
[Pub/Sub quickstart using
client libraries](https://docs.cloud.google.com/pubsub/docs/quickstart-client-libraries).


For more information, see the
[Pub/Sub PHP API
reference documentation](https://googleapis.github.io/google-cloud-php/#/docs/latest/pubsub/pubsubclient).


To authenticate to Pub/Sub, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```php
use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 */
function delete_subscription($projectId, $subscriptionName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $subscription = $pubsub->subscription($subscriptionName);
    $subscription->delete();

    printf('Subscription deleted: %s' . PHP_EOL, $subscription->name());
}
```

### Python


Before trying this sample, follow the Python setup instructions in the
[Pub/Sub quickstart using
client libraries](https://docs.cloud.google.com/pubsub/docs/quickstart-client-libraries).


For more information, see the
[Pub/Sub Python API
reference documentation](https://docs.cloud.google.com/python/docs/reference/pubsub/latest).


To authenticate to Pub/Sub, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```python
import google.api_core.exceptions
from google.cloud import pubsub_v1

client = pubsub_v1.SubscriberClient()


def delete_subscription(project_id: str, sub_id: str) -> None:
    """Deletes a Pub/Sub subscription.

    Args:
        project_id: The Google Cloud project ID (for example, 'example-project-id')
        sub_id: ID of the Sub (for example, 'example-sub-id')
    """
    subscription = client.subscription_path(project_id, sub_id)

    try:
        client.delete_subscription(request={"subscription": subscription})
        print(f"Subscription deleted: {subscription}")
    except google.api_core.exceptions.NotFound:
        print(f"Subscription {subscription} not found.")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"Failed to delete subscription {subscription}: {e}")
```

### Ruby


Before trying this sample, follow the Ruby setup instructions in the
[Pub/Sub quickstart using
client libraries](https://docs.cloud.google.com/pubsub/docs/quickstart-client-libraries).


For more information, see the
[Pub/Sub Ruby API
reference documentation](https://googleapis.dev/ruby/google-cloud-pubsub/latest/Google/Cloud/PubSub.html).


To authenticate to Pub/Sub, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```ruby
# subscription_id = "your-subscription-id"

pubsub = Google::Cloud::PubSub.new
subscription_admin = pubsub.subscription_admin

subscription_admin.delete_subscription \
  subscription: pubsub.subscription_path(subscription_id)

puts "Subscription #{subscription_id} deleted."
```

### Rust

```rust
use google_cloud_pubsub::client::SubscriptionAdmin;

pub async fn sample(
    client: &SubscriptionAdmin,
    project_id: &str,
    subscription_id: &str,
) -> anyhow::Result<()> {
    let subscription_name = format!("projects/{project_id}/subscriptions/{subscription_id}");

    client
        .delete_subscription()
        .set_subscription(subscription_name)
        .send()
        .await?;

    println!("successfully deleted subscription");
    Ok(())
}
```

## What's next


To search and filter code samples for other Google Cloud products, see the
[Google Cloud sample browser](https://docs.cloud.google.com/docs/samples.md.txt?product=pubsub).