Help Center/ Simple Message Notification/ API Reference/ Examples/ Example 1: Publishing Messages to a Topic
Updated on 2022-12-12 GMT+08:00

Example 1: Publishing Messages to a Topic

Scenarios

This section describes how to publish messages by calling APIs. For details, see Calling APIs.

Procedure

  1. Obtain the token by following instructions in Authentication.
  2. Create a topic.
    1. Send request POST https://{SMN_Endpoint}/v2/{project_id}/notifications/topics.
    2. Add X-Auth-Token to the request header.
    3. Specify the following parameters in the request body:
      For details about the parameters, see Creating a Topic.
      {
          "name": "test_topic_v2", //(Mandatory) Topic name
          "display_name": "test", //(Optional) Display name
          "enterprise_project_id": "0" //Enterprise project ID (mandatory in the enterprise project scenario)
      }
      Example response
      {     
          "request_id": "6a63a18b8bab40ffb71ebd9cb80d0085",     
          "topic_urn": "urn:smn:regionId:f96188c7ccaf4ffba0c9aa149ab2bd57:test_topic_v2" 
      }
  3. Add a subscription.
    1. Send request POST https://{SMN_Endpoint}/v2/{project_id}/notifications/topics/{topic_urn}/subscriptions.

      Set topic_urn based on the response in 2.c.

    2. Add X-Auth-Token to the request header.
    3. Specify the following parameters in the request body:
      {     
          "protocol": "email", //(Mandatory) Subscription protocol
          "endpoint": "xxx@xx.com", //(Mandatory) Email address
          "remark": "Subscription" //(Optional) Description
      }
      Example response
      {
          "subscriptions_result": [{
              "request_id": "126c17f805934e5eadf647b0860c7a0a",
              "subscription_urn": "urn:smn:regionId:f96188c7ccaf4ffba0c9aa149ab2bd57:test_topic_v2",
              "http_code": 201}]
      }

      You can add multiple subscriptions to a topic.

    4. The subscription endpoint receives a confirmation message, and you must confirm the subscription in the email.
  4. Publish a message.
    1. Send request POST https://{SMN_Endpoint}/v2/{project_id}/notifications/topics/{topic_urn}/publish.
    2. Add X-Auth-Token to the request header.
    3. Specify the following parameters in the request body:
      {    
         "subject":"test message v2", //(Optional) Message subject, which is displayed in email messages
         "message": "Message test message v2." //(Mandatory) Message to be published
      }

      Example response

      {    
          "request_id": "6a63a18b8bab40ffb71ebd9cb80d0085",   
          "message_id": "992bbd32819448af95f83814cb3c7454"  
      }

      Only confirmed subscription endpoints can receive the message you publish.