Method: users.watch
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Configurar ou atualizar uma observação de notificação push na caixa de correio do usuário.
Solicitação HTTP
POST https://gmail.googleapis.com/gmail/v1/users/{userId}/watch
O URL usa a sintaxe de transcodificação gRPC.
Parâmetros de caminho
Parâmetros |
userId |
string
O endereço de e-mail do usuário. O valor especial me pode ser usado para indicar o usuário autenticado.
|
Corpo da solicitação
O corpo da solicitação contém dados com a seguinte estrutura:
Campos |
labelIds[] |
string
Lista de labelIds para restringir notificações. Por padrão, se não for especificado, todas as mudanças serão enviadas. Se especificado, determina quais rótulos são necessários para gerar uma notificação push.
|
labelFilterAction (deprecated) |
enum (LabelFilterAction )
O comportamento de filtragem de labelIds list foi especificado. Este campo foi descontinuado porque causava um comportamento incorreto em alguns casos. Use labelFilterBehavior .
|
labelFilterBehavior |
enum (LabelFilterAction )
O comportamento de filtragem de labelIds list foi especificado. Esse campo substitui labelFilterAction . Se definido, labelFilterAction será ignorado.
|
topicName |
string
Um nome de tópico da API Google Cloud Pub/Sub totalmente qualificado para publicar os eventos. O nome do tópico precisa já existir no Cloud Pub/Sub, e você precisa ter concedido a permissão "publicar" do Gmail nele. Por exemplo, "projects/my-project-identifier/topics/my-topic-name" (usando o formato de nomenclatura de tópico "v1" do Cloud Pub/Sub). A parte "my-project-identifier" precisa corresponder exatamente ao ID do projeto do Google Developer (aquele que está executando essa solicitação de relógio).
|
Corpo da resposta
Resposta do relógio a uma notificação push.
Se bem-sucedido, o corpo da resposta incluirá dados com a estrutura a seguir:
Representação JSON |
{
"historyId": string,
"expiration": string
} |
Campos |
historyId |
string
O ID do registro de histórico atual da caixa de correio.
|
expiration |
string (int64 format)
Quando o Gmail vai parar de enviar notificações para atualizações da caixa de correio (milis da época). Chame watch novamente antes desse período para renovar o relógio.
|
Escopos de autorização
Requer um dos seguintes escopos do OAuth:
https://mail.google.com/
https://www.googleapis.com/auth/gmail.modify
https://www.googleapis.com/auth/gmail.readonly
https://www.googleapis.com/auth/gmail.metadata
Para mais informações, consulte o guia de autorização.
LabelFilterAction
O comportamento de filtragem da lista de labelIds foi especificado.
Enums |
include |
Receber notificações push apenas para mudanças de mensagens relacionadas aos labelIds especificados. |
exclude |
Receba notificações push para todas as mudanças de mensagem, exceto as relacionadas aos labelIds especificados. |
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
Última atualização 2025-07-25 UTC.
[null,null,["Última atualização 2025-07-25 UTC."],[],[],null,["# Method: users.watch\n\n- [HTTP request](#body.HTTP_TEMPLATE)\n- [Path parameters](#body.PATH_PARAMETERS)\n- [Request body](#body.request_body)\n - [JSON representation](#body.request_body.SCHEMA_REPRESENTATION)\n- [Response body](#body.response_body)\n - [JSON representation](#body.WatchResponse.SCHEMA_REPRESENTATION)\n- [Authorization scopes](#body.aspect)\n- [LabelFilterAction](#LabelFilterAction)\n\nSet up or update a push notification watch on the given user mailbox.\n\n### HTTP request\n\n`POST https://gmail.googleapis.com/gmail/v1/users/{userId}/watch`\n\nThe URL uses [gRPC Transcoding](https://google.aip.dev/127) syntax.\n\n### Path parameters\n\n| Parameters ||\n|----------|-----------------------------------------------------------------------------------------------------------|\n| `userId` | `string` The user's email address. The special value `me` can be used to indicate the authenticated user. |\n\n### Request body\n\nThe request body contains data with the following structure:\n\n| JSON representation |\n|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| ``` { \"labelIds\": [ string ], \"labelFilterAction\": enum (/workspace/gmail/api/reference/rest/v1/users/watch#LabelFilterAction), \"labelFilterBehavior\": enum (/workspace/gmail/api/reference/rest/v1/users/watch#LabelFilterAction), \"topicName\": string } ``` |\n\n| Fields ||\n|--------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `labelIds[]` | `string` List of labelIds to restrict notifications about. By default, if unspecified, all changes are pushed out. If specified then dictates which labels are required for a push notification to be generated. |\n| `labelFilterAction` **(deprecated)** | `enum (`[LabelFilterAction](/workspace/gmail/api/reference/rest/v1/users/watch#LabelFilterAction)`)` Filtering behavior of `labelIds list` specified. This field is deprecated because it caused incorrect behavior in some cases; use `labelFilterBehavior` instead. |\n| `labelFilterBehavior` | `enum (`[LabelFilterAction](/workspace/gmail/api/reference/rest/v1/users/watch#LabelFilterAction)`)` Filtering behavior of `labelIds list` specified. This field replaces `labelFilterAction`; if set, `labelFilterAction` is ignored. |\n| `topicName` | `string` A fully qualified Google Cloud Pub/Sub API topic name to publish the events to. This topic name **must** already exist in Cloud Pub/Sub and you **must** have already granted gmail \"publish\" permission on it. For example, \"projects/my-project-identifier/topics/my-topic-name\" (using the Cloud Pub/Sub \"v1\" topic naming format). Note that the \"my-project-identifier\" portion must exactly match your Google developer project id (the one executing this watch request). |\n\n### Response body\n\nPush notification watch response.\n\nIf successful, the response body contains data with the following structure:\n\n| JSON representation |\n|-------------------------------------------------------|\n| ``` { \"historyId\": string, \"expiration\": string } ``` |\n\n| Fields ||\n|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `historyId` | `string` The ID of the mailbox's current history record. |\n| `expiration` | `string (`[int64](https://developers.google.com/discovery/v1/type-format)` format)` When Gmail will stop sending notifications for mailbox updates (epoch millis). Call `watch` again before this time to renew the watch. |\n\n### Authorization scopes\n\nRequires one of the following OAuth scopes:\n\n- `https://mail.google.com/`\n- `\n https://www.googleapis.com/auth/gmail.modify`\n- `\n https://www.googleapis.com/auth/gmail.readonly`\n- `\n https://www.googleapis.com/auth/gmail.metadata`\n\nFor more information, see the [Authorization guide](/workspace/guides/configure-oauth-consent).\n\nLabelFilterAction\n-----------------\n\nFiltering behavior of labelIds list specified.\n\n| Enums ||\n|-----------|---------------------------------------------------------------------------------------------|\n| `include` | Only get push notifications for message changes relating to labelIds specified. |\n| `exclude` | Get push notifications for all message changes except those relating to labelIds specified. |"]]