Search for spaces

This guide explains how to use the search() method on the Space resource of the Google Chat API to search for named spaces in a Google Workspace organization.

The Space resource represents a place where people and Chat apps can send messages, share files, and collaborate. There are several types of spaces:

  • Direct messages (DMs) are conversations between two users or a user and a Chat app.
  • Group chats are conversations between three or more users and Chat apps.
  • Named spaces are persistent places where people send messages, share files, and collaborate.

If you are a Google Workspace administrator and want to search across all spaces in your organization, including private spaces you haven't joined, see Search for and manage spaces as a Google Workspace administrator to call the API with administrator privileges (useAdminAccess=true).

When searching for spaces with user authentication without administrator privileges, the method searches named spaces (spaceType of SPACE) that the authenticated user has access to, such as spaces they are a member of, within their organization.

Prerequisites

Node.js

Python

Java

Apps Script

Search for spaces with user authentication

To search for spaces in Google Chat without administrator privileges, pass the following in your request:

  • With user authentication, specify the chat.spaces.readonly or chat.spaces authorization scope.
  • Call the search() method on the Space resource.
  • Set useAdminAccess to false (or omit the parameter).
  • Specify the search query parameters to filter the results:
    • spaceType = "SPACE" - required when query is specified and the only supported value is SPACE.
    • displayName - filter by space display name using the HAS (:) operator. For example, displayName:"Project". The text to match is tokenized and each token is prefix-matched case-insensitively and independently as a substring anywhere in the space's displayName. Note: When useAdminAccess is false, displayName is required in your query to retrieve meaningful results; otherwise, the method returns an empty response.
    • externalUserAllowed - optionally filter by whether external guests are allowed in the space (true or false).
  • Optionally, specify pageSize to limit the maximum number of spaces to return (up to 1000), or pageToken to retrieve subsequent pages of results.
  • Optionally, specify orderBy to sort the search results (createTime desc or relevance desc). Note: relevance desc is available through the Google Workspace Developer Preview Program.

Across different fields in the query, only AND operators are supported. For example: spaceType = "SPACE" AND displayName:"Hello" AND externalUserAllowed = "true". Within displayName and externalUserAllowed, OR operators are supported if you want to match multiple criteria.

The following example searches for named spaces that contain "Project" in their display name:

Node.js

/**
 * This sample shows how to search for spaces without administrator privileges.
 *
 * It relies on the @google-apps/chat npm package.
 */
// Read the documentation for more details:
// https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search

const {ChatServiceClient} = require('@google-apps/chat');
const {auth} = require('google-auth-library');

async function main() {
  // Create a client
  const chatClient = new ChatServiceClient({
    authClient: await auth.getClient({
      scopes: ['https://www.googleapis.com/auth/chat.spaces.readonly']
    })
  });

  // Initialize request arguments.
  // When useAdminAccess is false, spaceType and displayName are required in query.
  const request = {
    query: 'spaceType = "SPACE" AND displayName:"Project"',
    useAdminAccess: false
  };

  // Call the API and iterate over the paginated response
  const iterable = chatClient.searchSpacesAsync(request);
  for await (const result of iterable) {
    console.log('Found space:', result.space.displayName, result.space.name);
  }
}

main().catch(console.error);

Python

"""
This sample shows how to search for spaces without administrator privileges.
"""
from google.apps import chat_v1
import google.auth

# Read the documentation for more details:
# https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search

def search_spaces():
    # Create a client
    scopes = ["https://www.googleapis.com/auth/chat.spaces.readonly"]
    credentials, _ = google.auth.default(scopes=scopes)
    client = chat_v1.ChatServiceClient(credentials=credentials)

    # Initialize request arguments.
    # When use_admin_access is False, space_type and display_name are required in query.
    request = chat_v1.SearchSpacesRequest(
        query='spaceType = "SPACE" AND displayName:"Project"',
        use_admin_access=False
    )

    # Make the request and iterate over the paginated results.
    page_result = client.search_spaces(request)
    for result in page_result.results:
        print(f"Found space: {result.space.display_name} ({result.space.name})")

if __name__ == "__main__":
    search_spaces()

Java

/**
 * This sample shows how to search for spaces without administrator privileges.
 */
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.ChatServiceClient.SearchSpacesPagedResponse;
import com.google.chat.v1.SearchSpacesRequest;
import com.google.chat.v1.SearchSpaceResult;

// Read the documentation for more details:
// https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search

public class SearchSpaces {
  public static void main(String[] args) throws Exception {
    // See https://github.com/googleworkspace/java-samples/blob/main/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/AuthenticationUtils.java
    // for an example of how to authenticate the request.
    try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials(
        ImmutableList.of("https://www.googleapis.com/auth/chat.spaces.readonly"))) {
      SearchSpacesRequest request = SearchSpacesRequest.newBuilder()
          .setQuery("spaceType = \"SPACE\" AND displayName:\"Project\"")
          .setUseAdminAccess(false)
          .build();

      SearchSpacesPagedResponse response = chatServiceClient.searchSpaces(request);

      for (SearchSpaceResult result : response.iterateAll()) {
        System.out.printf("Found space: %s (%s)\n", result.space.getDisplayName(), result.space.getName());
      }
    }
  }
}

Apps Script

/**
 * This sample shows how to search for spaces without administrator privileges.
 */
// Read the documentation for more details:
// https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search

function searchSpaces() {
  try {
    // Call the API
    // When useAdminAccess is false, spaceType and displayName are required in query.
    const response = Chat.Spaces.search({
      query: 'spaceType = "SPACE" AND displayName:"Project"',
      useAdminAccess: false
    });

    if (response.results && response.results.length > 0) {
      response.results.forEach(result => {
        console.log('Found space: %s (%s)', result.space.displayName, result.space.name);
      });
    } else {
      console.log('No matching spaces found.');
    }
  } catch (err) {
    console.log('Failed to search spaces: ' + err.message);
  }
}

The Chat API returns a paginated list of spaces that match the query and are accessible to the calling user.