Get a schema resource.

## Explore further


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

- [View the details of a schema](https://docs.cloud.google.com/pubsub/docs/view-schema-details.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::GetSchemaRequest request;
  request.set_name(pubsub::Schema(project_id, schema_id).FullName());
  request.set_view(google::pubsub::v1::FULL);
  auto schema = client.GetSchema(request);
  if (!schema) throw std::move(schema).status();

  std::cout << "The schema exists and its metadata is:" << "\n"
            << schema->DebugString() << "\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 GetSchemaSample
{
    public Schema GetSchema(string projectId, string schemaId)
    {
        SchemaServiceClient schemaService = SchemaServiceClient.Create();
        GetSchemaRequest request = new GetSchemaRequest
        {
            SchemaName = SchemaName.FromProjectSchema(projectId, schemaId),
            View = SchemaView.Full
        };

        return schemaService.GetSchema(request);
    }
}
```

### 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 getSchema(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()

	// Retrieve the full schema view. If you don't want to retrieve the
	// definition, pass in pubsubpb.SchemaView_BASIC which retrieves
	// just the name and type of the schema.
	req := &pubsubpb.GetSchemaRequest{
		Name: fmt.Sprintf("projects/%s/schemas/%s", projectID, schemaID),
		View: pubsubpb.SchemaView_FULL,
	}
	s, err := client.GetSchema(ctx, req)
	if err != nil {
		return fmt.Errorf("client.GetSchema: %w", err)
	}
	fmt.Fprintf(w, "Got schema: %#v\n", s)
	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.Schema;
import com.google.pubsub.v1.SchemaName;
import java.io.IOException;

public class GetSchema {

  public static void getSchema(String projectId, String schemaId) throws IOException {
    try (SchemaServiceClient client = SchemaServiceClient.create()) {
      String name = SchemaName.of(projectId, schemaId).toString();
      Schema schema = client.getSchema(name);

      System.out.println("Schema retrieved successfully: " + schema.getName());
      System.out.println("Type: " + schema.getType());
      System.out.println("Definition: " + schema.getDefinition());
    }
  }
}
```

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

    ]

    exports['command line option "outputpath" causes the output to move 1'] = [

### 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 getSchema(schemaNameOrId: string) {
      const schema = pubSubClient.schema(schemaNameOrId);
      const info = await schema.get();
      const fullName = await schema.getName();
      console.log(`Schema ${fullName} info: ${JSON.stringify(info, null, 4)}.`);
    }

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

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

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

    printf('Schema %s retrieved', $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 get_schema(project_id: str, schema_id: str) -> None:
    """Use the get_schema method

    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:
        response = client.get_schema(request={"name": name})
        print(f"Retrieved schema: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to retrieve schema: {error}")
```

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

schema = schemas.get_schema name: pubsub.schema_path(schema_id)

puts "Schema #{schema.name} retrieved."
```

### Rust

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

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

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