v1 Create a schema when you create a topic (DEPRECATED)

(DEPRECATED) Create a schema when you create a topic

Code sample

Go

Before trying this sample, follow the Go setup instructions in the Pub/Sub quickstart using client libraries . For more information, see the Pub/Sub Go API reference documentation .

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

  import 
  
 ( 
  
 "context" 
  
 "fmt" 
  
 "io" 
  
 "cloud.google.com/go/pubsub" 
 ) 
 func 
  
 createTopicWithSchema 
 ( 
 w 
  
 io 
 . 
 Writer 
 , 
  
 projectID 
 , 
  
 topicID 
 , 
  
 schemaID 
  
 string 
 , 
  
 encoding 
  
 pubsub 
 . 
  SchemaEncoding 
 
 ) 
  
 error 
  
 { 
  
 // projectID := "my-project-id" 
  
 // topicID := "my-topic" 
  
 // schemaID := "my-schema-id" 
  
 // encoding := pubsub.EncodingJSON 
  
 ctx 
  
 := 
  
 context 
 . 
 Background 
 () 
  
 client 
 , 
  
 err 
  
 := 
  
 pubsub 
 . 
  NewClient 
 
 ( 
 ctx 
 , 
  
 projectID 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "pubsub.NewClient: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 tc 
  
 := 
  
& pubsub 
 . 
 TopicConfig 
 { 
  
 SchemaSettings 
 : 
  
& pubsub 
 . 
 SchemaSettings 
 { 
  
 Schema 
 : 
  
 fmt 
 . 
 Sprintf 
 ( 
 "projects/%s/schemas/%s" 
 , 
  
 projectID 
 , 
  
 schemaID 
 ), 
  
 Encoding 
 : 
  
 encoding 
 , 
  
 }, 
  
 } 
  
 t 
 , 
  
 err 
  
 := 
  
 client 
 . 
  CreateTopicWithConfig 
 
 ( 
 ctx 
 , 
  
 topicID 
 , 
  
 tc 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 return 
  
 fmt 
 . 
 Errorf 
 ( 
 "CreateTopicWithConfig: %w" 
 , 
  
 err 
 ) 
  
 } 
  
 fmt 
 . 
 Fprintf 
 ( 
 w 
 , 
  
 "Topic with schema created: %#v\n" 
 , 
  
 t 
 ) 
  
 return 
  
 nil 
 } 
 

Ruby

Before trying this sample, follow the Ruby setup instructions in the Pub/Sub quickstart using client libraries . For more information, see the Pub/Sub Ruby API reference documentation .

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

  # topic_id = "your-topic-id" 
 # schema_id = "your-schema-id" 
 # Choose either BINARY or JSON as valid message encoding in this topic. 
 # message_encoding = :binary 
 pubsub 
  
 = 
  
 Google 
 :: 
 Cloud 
 :: 
  Pubsub 
 
 . 
 new 
 topic 
  
 = 
  
 pubsub 
 . 
 create_topic 
  
 topic_id 
 , 
  
 schema_name 
 : 
  
 schema_id 
 , 
  
 message_encoding 
 : 
  
 message_encoding 
 puts 
  
 "Topic 
 #{ 
 topic 
 . 
 name 
 } 
 created." 
 

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser .

Create a Mobile Website
View Site in Mobile | Classic
Share by: