Receive messages from a pull subscription

This document describes how to receive messages from a pull subscription. You can use the Google Cloud console, the Google Cloud CLI, the client library, or the Pub/Sub API to create a pull subscription.

Before you begin

Required roles and permissions

To get the permission that you need to receive messages from a pull subscription, ask your administrator to grant you the Pub/Sub Subscriber (roles/pubsub.subscriber) IAM role on the subscription. For more information about granting roles, see Manage access to projects, folders, and organizations.

This predefined role contains the pubsub.subscriptions.consume permission, which is required to receive messages from a pull subscription.

You might also be able to get this permission with custom roles or other predefined roles.

Pull a message from a subscription

The following samples demonstrate how to pull a message from a subscription using either the StreamingPull API or the Pull API.

StreamingPull API

To use the StreamingPull API, you must use a client library.

The Google Cloud console and Google Cloud CLI don't support the StreamingPull API.

StreamingPull and high-level client library code samples

C++

Before trying this sample, follow the C++ setup instructions in Quickstart: Using Client Libraries. For more information, see the Pub/Sub C++ API reference documentation.

namespace pubsub = ::google::cloud::pubsub;
auto sample = [](pubsub::Subscriber subscriber) {
  return subscriber.Subscribe(
      [&](pubsub::Message const& m, pubsub::AckHandler h) {
        std::cout << "Received message " << m << "\n";
        std::move(h).ack();
        PleaseIgnoreThisSimplifiesTestingTheSamples();
      });
};

C#

Before trying this sample, follow the C# setup instructions in Quickstart: Using Client Libraries. For more information, see the Pub/Sub C# API reference documentation.


using Google.Cloud.PubSub.V1;
using System;
using System.Threading;
using System.Threading.Tasks;

public class PullMessagesAsyncSample
{
    public async Task<int> PullMessagesAsync(string projectId, string subscriptionId, bool acknowledge)
    {