Delete a schema resource.

## Explore further


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

- [Delete a schema for a topic](https://docs.cloud.google.com/pubsub/docs/delete-schema.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 = ::google::cloud::pubsub;
[](pubsub::SchemaServiceClient client, std::string const& project_id,
   std::string const& schema_id) {
  google::pubsub::v1::DeleteSchemaRequest request;
  request.set_name(pubsub::Schema(project_id, schema_id).FullName());
  auto status = client.DeleteSchema(request);
  // Note that kNotFound is a possible result when the library retries.
  if (status.code() == google::cloud::StatusCode::kNotFound) {
    std::cout << "The schema was not found\n";
    return;
  }
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "Schema 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 DeleteSchemaSample
{
    public void DeleteSchema(string projectId, string schemaId)
    {
        SchemaServiceClient schemaService = SchemaServiceClient.Create();
        SchemaName schemaName = SchemaName.FromProjectSchema(projectId, schemaId);
        schemaService.DeleteSchema(schemaName);
    }
}
```

### 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"

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

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

	req := &pubsubpb.DeleteSchemaRequest{
		Name: fmt.Sprintf("projects/%s/schemas/%s", projectID, schemaID),
	}
	if err := client.DeleteSchema(ctx, req); err != nil {
		return fmt.Errorf("client.DeleteSchema: %w", err)
	}
	fmt.Fprintf(w, "Deleted schema: %s", schemaID)
	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.SchemaServiceClient;
import com.google.pubsub.v1.SchemaName;

public class DeleteSchema {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project-id";
    String schemaId = "example-schema-id";
    deleteSchema(projectId, schemaId);
  }

  public static void deleteSchema(String projectId, String schemaId) throws Exception {
    try (SchemaServiceClient client = SchemaServiceClient.create()) {
      String name = SchemaName.of(projectId, schemaId).toString();
      client.deleteSchema(name);
      System.out.println("Deleted schema: " + name);
    }
  }
}
```

### 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).

    'use strict';

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

    const client = new SchemaServiceClient();

    /**
     * Use the deleteSchema method
     *
     * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id')
     * @param {string} schemaId - ID of the Schema (for example, 'example-schema-id')
     */
    async function deleteSchema(projectId, schemaId) {
      try {
        // Format the resource name from project and schema identifiers
        const name = client.schemaPath(projectId, schemaId);

        const request = {
          name,
        };

        await client.deleteSchema(request);
        console.log(`Deleted schema: ${name}`);
      } catch (err) {
        if (err.code === status.NOT_FOUND) {
          console.error(`Schema not found: ${projectId}/${schemaId}`);
        } else if (err.code === status.PERMISSION_DENIED) {
          console.error(`Permission denied for schema: ${projectId}/${schemaId}`);
        } else {
          console.error(`Failed to delete schema: ${err.message}`);
        }
      }
    }

    module.exports = { deleteSchema };

### 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).

    /**
     * TODO(developer): Uncomment this variable before running the sample.
     */
    // const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID';

    // Imports the Google Cloud client library
    import {PubSub} from '@google-cloud/pubsub';

    // Creates a client; cache this for further use
    const pubSubClient = new PubSub();

    async function deleteSchema(schemaNameOrId: string) {
      const schema = pubSubClient.schema(schemaNameOrId);
      const name = await schema.getName();
      await schema.delete();
      console.log(`Schema ${name} deleted.`);
    }

### 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;

/**
 * Delete a schema.
 *
 * @param string $projectId
 * @param string $schemaId
 */
function delete_schema($projectId, $schemaId)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);

    $schema = $pubsub->schema($schemaId);

    if ($schema->exists()) {
        $schema->delete();

        printf('Schema %s deleted.', $schema->name());
    } else {
        printf('Schema %s does not exist.', $schema->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.SchemaServiceClient()


def delete_schema(project_id: str, schema_id: str) -> None:
    """Deletes a Pub/Sub schema.

    Args:
        project_id: The Google Cloud project ID (for example, 'example-project-id')
        schema_id: ID of the Schema (for example, 'example-schema-id')
    """
    name = client.schema_path(project_id, schema_id)

    try:
        client.delete_schema(name=name)
        print(f"Deleted schema: {name}")
    except google.api_core.exceptions.NotFound:
        print(f"Schema does not exist: {name}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"Failed to delete schema due to an API error: {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
# schema_id = "your-schema-id"

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

result = schemas.delete_schema name: pubsub.schema_path(schema_id)

puts "Schema #{schema_id} deleted."
```

### Rust

```rust
use google_cloud_pubsub::client::SchemaService;

pub async fn sample(
    client: &SchemaService,
    project_id: &str,
    schema_id: &str,
) -> anyhow::Result<()> {
    client
        .delete_schema()
        .set_name(format!("projects/{project_id}/schemas/{schema_id}"))
        .send()
        .await?;

    println!("successfully deleted schema");
    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).