Apigee X: Publish Message to PubSub Topic

Hi, how can I publish a json body from a request to a PubSub topic with attributes?

 

1 2 482
2 REPLIES 2

You're right the PublishMessage policy currently only supports the topic but no attributes to be specified when publishing to Pub/Sub.

The most flexible approach would be to use a service callout policy with Google Authentication to publish to the Pub/Sub REST endpoint.
Alternatively if you need more logic to be applied you could also create a Cloud Run application and call that one from Apigee.

As a ServiceCallout, this would look something like this:

 

<ServiceCallout name='SC-PublishMessage'>
  <Request variable='myrequestvariable'>
    <Set>
      <Verb>POST</Verb>
      <Payload contentType='application/json'>{
  "data": "whatever",
  "attributes": {
    "name1": "value1",
    "name2": "value2",
    ...
  },
  ..
}
</Payload>
    </Set>
  </Request>

  <Response>pubsubResponse</Response>

  <HTTPTargetConnection>

    <!-- this will use the Service Account you specified at deployment time -->
    <Authentication>
      <GoogleAccessToken>
        <Scopes>
          <Scope>https://www.googleapis.com/auth/pubsub</Scope>
        </Scopes>
      </GoogleAccessToken>
    </Authentication>

    <SSLInfo>
        <Enabled>true</Enabled>
        <IgnoreValidationErrors>false</IgnoreValidationErrors>
    </SSLInfo>
    <Properties>
      <Property name='success.codes'>2xx, 3xx</Property>
    </Properties>
    <URL>https://pubsub.googleapis.com/v1/projects/{gcp-project}/topics/{pubsub-topic}:publish</URL>
  </HTTPTargetConnection>
</ServiceCallout>

 

It's my understanding that the data value must be base64 encoded.