Updated on 2024-04-19 GMT+08:00

Getting Started

Scenarios

This topic describes how to publish a message to a topic by calling APIs.

For details about how to call APIs, see Calling APIs.

The token obtained from IAM is valid for only 24 hours. If you want to use one token for authentication, you can cache it to avoid frequently calling the IAM API.

Involved APIs

To use token authentication, you need to obtain a token and add X-Auth-Token to the request header of API calls.

  • IAM API to obtain a token
  • SMN API to create a topic
  • SMN API to add subscriptions
  • SMN API to publish messages

Procedure

  1. Obtain the token by referring to Authentication.
  2. Send a request POST https://{SMN_Endpoint}/v2/{project_id}/notifications/topics to create a topic.
    1. Add X-Auth-Token to the request header.
    2. Specify the following parameters in the request body:
      {
          "name": "test_topic_v2", // Topic name (mandatory)
          "display_name": "test"  // Display name (optional)
      }

      If the request is successful, a request ID (request_id) and topic URN (topic_urn) are returned.

      If the request fails, an error code and error information are returned. For details, see Error Codes.

  3. Send a request POST https://{SMN_Endpoint}/v2/{project_id}/notifications/topics/{topic_urn}/subscriptions to add subscriptions.

    Set topic_urn based on the response in 2.b.

    1. Add X-Auth-Token to the request header.
    2. Specify the following parameters in the request body:
      {
          "protocol": "email", // Subscription protocol (mandatory)
          "endpoint": "xxx@xx.com", // Email address (mandatory)
          "remark": "Subscription" // Description (optional)
      }

      If the request is successful, a request ID (request_id) and subscription URN (subscription_urn) are returned.

      If the request fails, an error code and error information are returned. For details, see Error Codes.

      You can add multiple kinds of subscriptions to a topic. For details, see Adding a Subscription.

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

      If the request is successful, a request ID (request_id) and message ID (message_id) are returned.

      If the request fails, an error code and error information are returned. For details, see Error Codes.

      Only confirmed subscription endpoints can receive the message you publish.