This guide explains how to use the
[`search()`](https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search) method on the
[`Space` resource](https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces) of the
Google Chat API to search for named spaces in a Google Workspace organization.

The
[`Space` resource](https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces)
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](https://developers.google.com/workspace/chat/search-manage-admin) to call the API with administrator privileges (`useAdminAccess=true`).

When searching for spaces with [user authentication](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user) 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

- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).

<!-- -->

- Set up your environment:
  - [Create a Google Cloud project](https://developers.google.com/workspace/guides/create-project).
  - [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent).
  - [Enable and configure the Google Chat API](https://developers.google.com/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.
  - Install the Node.js [Cloud Client Library](https://developers.google.com/workspace/chat/libraries?tab=nodejs#cloud-client-libraries).
  - [Create OAuth client ID credentials](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user#step-2:) for a desktop application. To run the sample in this guide, save the credentials as a JSON file named `credentials.json` to your local directory.

  For guidance, complete the steps for setting up your environment in this [quickstart](https://developers.google.com/workspace/chat/api/guides/quickstart/nodejs
  #set-up-environment).
- [Choose an authorization scope](https://developers.google.com/workspace/chat/authenticate-authorize#asynchronous-chat-calls) that supports user authentication.

### Python

- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).

<!-- -->

- Set up your environment:
  - [Create a Google Cloud project](https://developers.google.com/workspace/guides/create-project).
  - [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent).
  - [Enable and configure the Google Chat API](https://developers.google.com/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.
  - Install the Python [Cloud Client Library](https://developers.google.com/workspace/chat/libraries?tab=python#cloud-client-libraries).
  - [Create OAuth client ID credentials](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user#step-2:) for a desktop application. To run the sample in this guide, save the credentials as a JSON file named `credentials.json` to your local directory.

  For guidance, complete the steps for setting up your environment in this [quickstart](https://developers.google.com/workspace/chat/api/guides/quickstart/python
  #set-up-environment).
- [Choose an authorization scope](https://developers.google.com/workspace/chat/authenticate-authorize#asynchronous-chat-calls) that supports user authentication.

### Java

- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).

<!-- -->

- Set up your environment:
  - [Create a Google Cloud project](https://developers.google.com/workspace/guides/create-project).
  - [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent).
  - [Enable and configure the Google Chat API](https://developers.google.com/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.
  - Install the Java [Cloud Client Library](https://developers.google.com/workspace/chat/libraries?tab=java#cloud-client-libraries).
  - [Create OAuth client ID credentials](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user#step-2:) for a desktop application. To run the sample in this guide, save the credentials as a JSON file named `credentials.json` to your local directory.

  For guidance, complete the steps for setting up your environment in this [quickstart](https://developers.google.com/workspace/chat/api/guides/quickstart/java
  #set-up-environment).
- [Choose an authorization scope](https://developers.google.com/workspace/chat/authenticate-authorize#asynchronous-chat-calls) that supports user authentication.

### Apps Script

- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).

<!-- -->

- Set up your environment:
  - [Create a Google Cloud project](https://developers.google.com/workspace/guides/create-project).
  - [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent).
  - [Enable and configure the Google Chat API](https://developers.google.com/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.
  - [Create a standalone Apps Script project](https://developers.google.com/apps-script/guides/projects), and turn on the [Advanced Chat Service](https://developers.google.com/apps-script/advanced/chat).

  For steps to set up your environment, complete this [quickstart](https://developers.google.com/workspace/chat/api/guides/quickstart/apps-script).
- [Choose an authorization scope](https://developers.google.com/workspace/chat/authenticate-authorize#asynchronous-chat-calls) that supports user authentication.


> [!NOTE]
> The code samples in this page use the gRPC API interface with the Google Cloud client libraries. Alternatively, you can use the REST API interface. For more information about the gRPC and REST interfaces, see [Google Chat API overview](https://developers.google.com/workspace/chat/api/reference).

<br />

## 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](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user), specify the `chat.spaces.readonly` or `chat.spaces` authorization scope.
- Call the [`search()`](https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search) method on the `Space` resource.
- Set `useAdminAccess` to `false` (or omit the parameter).
- Specify the search [`query`](https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search#body.QUERY_PARAMETERS.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](https://developers.google.com/workspace/preview).

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](https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search#response-body) that match the query and are accessible to the calling user.

## Related topics

- [Create a space](https://developers.google.com/workspace/chat/create-spaces)
- [Set up a space](https://developers.google.com/workspace/chat/set-up-spaces)
- [Get details about a space](https://developers.google.com/workspace/chat/get-spaces)
- [List spaces](https://developers.google.com/workspace/chat/list-spaces)
- [Update a space](https://developers.google.com/workspace/chat/update-spaces)
- [Delete a space](https://developers.google.com/workspace/chat/delete-spaces)
- [Search for and manage spaces as a Google Workspace administrator](https://developers.google.com/workspace/chat/search-manage-admin)