Pub/Sub publish message
Stay organized with collections
Save and categorize content based on your preferences.
Demonstrates how to interact with Pub/Sub from Cloud Functions.
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis content showcases how to interact with Pub/Sub from Cloud Functions using code examples.\u003c/p\u003e\n"],["\u003cp\u003eThe code samples demonstrate publishing messages to a Pub/Sub topic in Java, Node.js, and Python.\u003c/p\u003e\n"],["\u003cp\u003eAuthentication for Cloud Run functions is required, and the Application Default Credentials can be set up for this purpose.\u003c/p\u003e\n"],["\u003cp\u003eThe code samples provided require the user to input topic name and the message.\u003c/p\u003e\n"]]],[],null,["# Pub/Sub publish message\n\nDemonstrates how to interact with Pub/Sub from Cloud Functions.\n\nCode sample\n-----------\n\n### Java\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import com.google.cloud.functions.HttpFunction;\n import com.google.cloud.functions.HttpRequest;\n import com.google.cloud.functions.HttpResponse;\n import com.google.cloud.pubsub.v1.https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/com.google.cloud.pubsub.v1.Publisher.html;\n import com.google.protobuf.https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html;\n import com.google.pubsub.v1.https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/com.google.pubsub.v1.ProjectTopicName.html;\n import com.google.pubsub.v1.https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/com.google.pubsub.v1.PubsubMessage.html;\n import java.io.BufferedWriter;\n import java.io.IOException;\n import java.net.HttpURLConnection;\n import java.nio.charset.StandardCharsets;\n import java.util.Optional;\n import java.util.concurrent.ExecutionException;\n import java.util.concurrent.TimeUnit;\n import java.util.logging.Level;\n import java.util.logging.Logger;\n\n public class PublishMessage implements HttpFunction {\n // TODO\u003cdeveloper\u003e set this environment variable\n private static final String PROJECT_ID = System.getenv(\"GOOGLE_CLOUD_PROJECT\");\n\n private static final Logger logger = Logger.getLogger(PublishMessage.class.getName());\n\n @Override\n public void service(HttpRequest request, HttpResponse response)\n throws IOException, InterruptedException {\n Optional\u003cString\u003e maybeTopicName = request.getFirstQueryParameter(\"topic\");\n Optional\u003cString\u003e maybeMessage = request.getFirstQueryParameter(\"message\");\n\n BufferedWriter responseWriter = response.getWriter();\n\n if (maybeTopicName.isEmpty() || maybeMessage.isEmpty()) {\n response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST);\n\n responseWriter.write(\"Missing 'topic' and/or 'message' parameter(s).\");\n return;\n }\n\n String topicName = maybeTopicName.get();\n logger.info(\"Publishing message to topic: \" + topicName);\n\n // Create the PubsubMessage object\n // (This is different than the PubsubMessage POJO used in Pub/Sub-triggered functions)\n https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html byteStr = https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html.https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html#com_google_protobuf_ByteString_copyFrom_byte___(maybeMessage.get(), StandardCharsets.UTF_8);\n https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/com.google.pubsub.v1.PubsubMessage.html pubsubApiMessage = https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/com.google.pubsub.v1.PubsubMessage.html.newBuilder().setData(byteStr).build();\n\n https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/com.google.cloud.pubsub.v1.Publisher.html publisher = https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/com.google.cloud.pubsub.v1.Publisher.html.newBuilder(\n https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/com.google.pubsub.v1.ProjectTopicName.html.of(PROJECT_ID, topicName)).build();\n\n // Attempt to publish the message\n String responseMessage;\n try {\n https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/com.google.cloud.pubsub.v1.Publisher.html#com_google_cloud_pubsub_v1_Publisher_publish_com_google_pubsub_v1_PubsubMessage_er.https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/com.google.cloud.pubsub.v1.Publisher.html#com_google_cloud_pubsub_v1_Publisher_publish_com_google_pubsub_v1_PubsubMessage_(pubsubApiMessage).get();\n responseMessage = \"Message published.\";\n } catch (InterruptedException | ExecutionException e) {\n logger.log(Level.SEVERE, \"Error publishing Pub/Sub message: \" + e.getMessage(), e);\n responseMessage = \"Error publishing Pub/Sub message; see logs for more info.\";\n } finally {\n if (publisher != null) {\n // When finished with the publisher, shutdown to free up resources.\n publisher.https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/com.google.cloud.pubsub.v1.Publisher.html#com_google_cloud_pubsub_v1_Publisher_shutdown__();\n publisher.https://cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/com.google.cloud.pubsub.v1.Publisher.html#com_google_cloud_pubsub_v1_Publisher_awaitTermination_long_java_util_concurrent_TimeUnit_(1, TimeUnit.MINUTES);\n }\n }\n\n responseWriter.write(responseMessage);\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const {PubSub} = require('https://cloud.google.com/nodejs/docs/reference/pubsub/latest/overview.html');\n\n // Instantiates a client\n const pubsub = new https://cloud.google.com/nodejs/docs/reference/pubsub/latest/pubsub/pubsub.html();\n\n /**\n * Publishes a message to a Cloud Pub/Sub Topic.\n *\n * @param {object} req Cloud Function request context.\n * @param {object} req.body The request body.\n * @param {string} req.body.topic Topic name on which to publish.\n * @param {string} req.body.message Message to publish.\n * @param {object} res Cloud Function response context.\n */\n exports.publish = async (req, res) =\u003e {\n if (!req.body.topic || !req.body.message) {\n res\n .status(400)\n .send(\n 'Missing parameter(s); include \"topic\" and \"message\" properties in your request.'\n );\n return;\n }\n\n console.log(`Publishing message to topic ${req.body.topic}`);\n\n // References an existing topic\n const topic = pubsub.topic(req.body.topic);\n\n const messageObject = {\n data: {\n message: req.body.message,\n },\n };\n const messageBuffer = Buffer.https://cloud.google.com/nodejs/docs/reference/pubsub/latest/pubsub/duration.html(https://cloud.google.com/nodejs/docs/reference/pubsub/latest/pubsub/protos.google.pubsub.v1.encoding.html.stringify(messageObject), 'utf8');\n\n // Publishes a message\n try {\n topic.https://cloud.google.com/nodejs/docs/reference/pubsub/latest/pubsub/topic.html(messageBuffer);\n res.status(200).send('Message published.');\n } catch (err) {\n console.error(err);\n res.status(500).send(err);\n return https://cloud.google.com/nodejs/docs/reference/pubsub/latest/pubsub/pubsub.html.reject(err);\n }\n };\n\n### Python\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import base64\n import json\n import os\n\n from google.cloud import pubsub_v1\n\n\n # TODO(developer): set this environment variable\n PROJECT_ID = os.getenv(\"GOOGLE_CLOUD_PROJECT\")\n\n\n # Instantiates a Pub/Sub client\n publisher = pubsub_v1.https://cloud.google.com/python/docs/reference/pubsublite/latest/google.cloud.pubsublite.cloudpubsub.publisher_client.PublisherClient.html()\n\n\n # Publishes a message to a Cloud Pub/Sub topic.\n def publish(request):\n request_json = request.get_json(silent=True)\n\n topic_name = request_json.get(\"topic\")\n message = request_json.get(\"message\")\n\n if not topic_name or not message:\n return ('Missing \"topic\" and/or \"message\" parameter.', 400)\n\n print(f\"Publishing message to topic {topic_name}\")\n\n # References an existing topic\n topic_path = publisher.topic_path(PROJECT_ID, topic_name)\n\n message_json = json.dumps(\n {\n \"data\": {\"message\": message},\n }\n )\n message_bytes = message_json.encode(\"utf-8\")\n\n # Publishes a message\n try:\n publish_future = https://cloud.google.com/python/docs/reference/pubsublite/latest/google.cloud.pubsublite.cloudpubsub.publisher_client.PublisherClient.htmler.https://cloud.google.com/python/docs/reference/pubsublite/latest/google.cloud.pubsublite.cloudpubsub.publisher_client.PublisherClient.html(topic_path, data=message_bytes)\n publish_future.result() # Verify the publish succeeded\n return \"Message published.\"\n except Exception as e:\n print(e)\n return (e, 500)\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]