É possível publicar um evento do CloudEvents diretamente em um barramento
do Eventarc Advanced em um formato compatível usando a Google Cloud CLI ou enviando uma solicitação para
a API REST de publicação do Eventarc. Você também pode usar as
bibliotecas de cliente do Eventarc
para acessar as APIs do Eventarc em uma linguagem compatível.
BUS_NAME: o ID ou identificador totalmente qualificado
do barramento em que o evento será publicado.
Use apenas uma das seguintes opções:
AVRO_MESSAGE: a mensagem de evento em um formato Avro
de acordo com esta
especificação.
JSON_MESSAGE: a mensagem de evento em formato JSON
de acordo com esta
especificação.
DATA_PAYLOAD: os dados de um evento publicado.
Se você estiver usando a flag --event-data, também precisará usar o seguinte:
EVENT_ID: o identificador do evento. Os produtores de eventos precisam garantir que source + id seja exclusivo para cada evento distinto.
EVENT_SOURCE: a origem do evento de um evento
publicado.
EVENT_TYPE: o tipo de evento relacionado à
ocorrência de origem.
Se você estiver usando a flag --event-data, poderá usar as seguintes opções:
EVENT_ATTRIBUTE: os atributos de um evento publicado.
Você pode repetir a flag --event-attributes para adicionar mais atributos.
Os eventos podem incluir qualquer número de atributos personalizados adicionais do CloudEvents com nomes distintos, também conhecidos como atributos de extensão.
Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:
O nome completo do recurso do ônibus no formato
projects/PROJECT_ID/locations/LOCATION/messageBuses/BUS_NAME
Substitua:
PROJECT_ID: o ID do projeto Google Cloud
do projeto de ônibus.
LOCATION: a região em que o barramento é implantado, por exemplo, us-central1.
BUS_NAME: o nome do barramento em que o evento será publicado.
SPEC_VERSION: a versão da especificação
CloudEvents que o evento usa. Por exemplo, 1.0.
EVENT_TYPE: o tipo de evento relacionado
à ocorrência de origem.
EVENT_SOURCE: a origem do evento de um
evento publicado.
EVENT_ID: o identificador do evento.
Os produtores precisam garantir que source + id seja exclusivo para cada evento distinto.
CONTENT_TYPE (opcional): o tipo de conteúdo do valor data. Se um evento no formato JSON não tiver um atributo datacontenttype, presume-se que os dados sejam um valor JSON em conformidade com o
tipo de mídia application/json.
DATA_PAYLOAD (opcional): o payload do evento codificado no formato de mídia especificado por datacontenttype e seguindo dataschema quando esses atributos estão presentes.
Para enviar a solicitação, expanda uma destas opções:
curl (Linux, macOS ou Cloud Shell)
Salve o corpo da solicitação em um arquivo chamado request.json.
Execute o comando a seguir no terminal para criar ou substituir
esse arquivo no diretório atual:
Salve o corpo da solicitação em um arquivo chamado request.json.
Execute o comando a seguir no terminal para criar ou substituir
esse arquivo no diretório atual:
Copie o corpo da solicitação e abra a
página de referência do método.
O painel "APIs Explorer" é aberto no lado direito da página.
Interaja com essa ferramenta para enviar solicitações.
Cole o corpo da solicitação nessa ferramenta, preencha todos os outros campos obrigatórios e clique em Executar.
Se a solicitação for bem-sucedida, o servidor vai retornar um código de status HTTP 200 OK e o corpo da resposta vazio no formato JSON:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-04 UTC."],[[["\u003cp\u003eEventarc Advanced allows direct publishing of CloudEvents to an Eventarc bus using the Google Cloud CLI or the Eventarc Publishing REST API.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003egcloud beta eventarc message-buses publish\u003c/code\u003e command facilitates event publishing, supporting Avro, JSON, or individual event data with attributes.\u003c/p\u003e\n"],["\u003cp\u003eThe REST API's \u003ccode\u003eprojects.locations.messageBuses.publish\u003c/code\u003e method can be used to publish events, requiring a JSON message body that specifies event attributes like \u003ccode\u003especversion\u003c/code\u003e, \u003ccode\u003etype\u003c/code\u003e, \u003ccode\u003esource\u003c/code\u003e, and \u003ccode\u003eid\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe gcloud CLI can be used through the terminal and the REST API through curl (Linux, macOS, or Cloud Shell), Powershell (Windows), and the API explorer (browser).\u003c/p\u003e\n"],["\u003cp\u003eEventarc Advanced is currently a Pre-GA feature and is subject to limited support.\u003c/p\u003e\n"]]],[],null,["# Publish events directly\n\n[Advanced](/eventarc/advanced/docs/overview)\n\nYou can publish a CloudEvents event directly to an Eventarc Advanced\nbus in a supported format using the Google Cloud CLI or by sending a request to\nthe Eventarc Publishing REST API. You can also use the\n[Eventarc client libraries](/eventarc/docs/reference/libraries)\nto access the Eventarc APIs from a supported language.\n\nBefore you begin\n----------------\n\nIf you haven't already, enable the [Eventarc API](/eventarc/docs/reference/rest)\nand the\n[Eventarc Publishing API](/eventarc/docs/reference/publishing/rest). \n\n```bash\ngcloud services enable eventarc.googleapis.com eventarcpublishing.googleapis.com\n```\n\nPublish directly\n----------------\n\nThe event message you publish directly must conform to the\n[CloudEvents specification](/eventarc/advanced/docs/event-format). \n\n### gcloud\n\n1. Open a terminal.\n\n2. You can publish events to a bus by using the\n [`gcloud eventarc message-buses publish`](/sdk/gcloud/reference/eventarc/message-buses/publish)\n command. For example:\n\n ```bash\n gcloud eventarc message-buses publish BUS_NAME \\\n --avro-message=AVRO_MESSAGE\n ```\n Or: \n\n ```bash\n gcloud eventarc message-buses publish BUS_NAME \\\n --json-message=JSON_MESSAGE\n ```\n Or: \n\n ```bash\n gcloud eventarc message-buses publish BUS_NAME \\\n --event-data=DATA_PAYLOAD \\\n --event-id=EVENT_ID \\\n --event-source=EVENT_SOURCE \\\n --event-type=EVENT_TYPE \\\n --event-attributes=EVENT_ATTRIBUTE\n ```\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003eBUS_NAME\u003c/var\u003e: the ID or fully qualified identifier of the bus to which to publish the event.\n\n You must use only *one* of the following:\n - \u003cvar translate=\"no\"\u003eAVRO_MESSAGE\u003c/var\u003e: the event message in an Avro format according to this [specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/formats/avro-format.md).\n - \u003cvar translate=\"no\"\u003eJSON_MESSAGE\u003c/var\u003e: the event message in a JSON format according to this [specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/formats/json-format.md).\n - \u003cvar translate=\"no\"\u003eDATA_PAYLOAD\u003c/var\u003e: the data of a published event.\n\n If using the `--event-data` flag, you must also use the following:\n - \u003cvar translate=\"no\"\u003eEVENT_ID\u003c/var\u003e: the event identifier. Event producers must ensure that `source` + `id` is unique for each distinct event.\n - \u003cvar translate=\"no\"\u003eEVENT_SOURCE\u003c/var\u003e: the event source of a published event.\n - \u003cvar translate=\"no\"\u003eEVENT_TYPE\u003c/var\u003e: the type of event related to the originating occurrence.\n\n If using the `--event-data` flag, you can optionally use the following:\n - \u003cvar translate=\"no\"\u003eEVENT_ATTRIBUTE\u003c/var\u003e: the attributes of a published event.\n You can repeat the `--event-attributes` flag to add more attributes.\n\n Note that events might include any number of additional custom\n CloudEvents attributes with distinct names (also known as\n [extension attributes](https://github.com/cloudevents/spec/blob/main/cloudevents/spec.md#extension-context-attributes)).\n\n### Examples:\n\n```bash\ngcloud eventarc message-buses publish my-bus \\\n --event-data='{\"key\": \"hello-world-data\"}' \\\n --event-id=hello-world-id-1234 \\\n --event-source=hello-world-source \\\n --event-type=hello-world-type \\\n --event-attributes=\"datacontenttype=application/json\"\n```\n\n\u003cbr /\u003e\n\n```bash\ngcloud eventarc message-buses publish my-bus --json-message='{\n \"specversion\" : \"1.0\",\n \"type\" :\"com.example.someevent\",\n \"source\" : \"google.cloud.storage.object.v1.finalized\",\n \"id\" : \"A234-1234-1234\",\n \"time\" : \"2024-04-05T17:31:00Z\",\n \"bucket\" : \"bucketName\",\n \"datacontenttype\" : \"application/json\",\n \"data\":{\"key\": \"value\"}\n}'\n```\n\n### REST API\n\nTo publish an event to a bus, use the\n[`projects.locations.messageBuses.publish`](/eventarc/docs/reference/publishing/rest/v1/projects.locations.messageBuses/publish)\nmethod.\n| **Note:** In the `ProtoMessage` of the request body, the `protoData` field only functions as expected when the payload is specifically a `CloudEvent` message type, and can't be used for arbitrary protocol buffer messages. For any other protocol buffer type, you must serialize your proto message into bytes, and use the `binaryData` field instead.\n\n\nBefore using any of the request data,\nmake the following replacements:\n\n- The full resource name of the bus in the format `projects/`\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e`/locations/`\u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e`/messageBuses/`\u003cvar translate=\"no\"\u003eBUS_NAME\u003c/var\u003e\n\n Replace the following:\n - \u003cvar class=\"edit\" scope=\"PROJECT_ID\" translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e: the Google Cloud project ID for the bus project.\n - \u003cvar class=\"edit\" scope=\"LOCATION\" translate=\"no\"\u003eLOCATION\u003c/var\u003e: the [region](/eventarc/docs/locations) in which the bus is deployed---for example, `us-central1`.\n - \u003cvar class=\"edit\" scope=\"BUS_NAME\" translate=\"no\"\u003eBUS_NAME\u003c/var\u003e: the name of the bus to which to publish the event.\n- \u003cvar class=\"edit\" scope=\"SPEC_VERSION\" translate=\"no\"\u003eSPEC_VERSION\u003c/var\u003e: the version of the CloudEvents specification which the event uses---for example, `1.0`.\n- \u003cvar class=\"edit\" scope=\"EVENT_TYPE\" translate=\"no\"\u003eEVENT_TYPE\u003c/var\u003e: the type of event related to the originating occurrence.\n- \u003cvar class=\"edit\" scope=\"EVENT_SOURCE\" translate=\"no\"\u003eEVENT_SOURCE\u003c/var\u003e: the event source of a published event.\n- \u003cvar class=\"edit\" scope=\"EVENT_ID\" translate=\"no\"\u003eEVENT_ID\u003c/var\u003e: the event identifier. Producers must ensure that `source` + `id` is unique for each distinct event.\n- \u003cvar class=\"edit\" scope=\"CONTENT_TYPE\" translate=\"no\"\u003eCONTENT_TYPE\u003c/var\u003e (optional): the content type of `data` value. If a JSON format event has no `datacontenttype` attribute, then it is assumed that the data is a JSON value conforming to the `application/json` media type.\n- \u003cvar class=\"edit\" scope=\"DATA_PAYLOAD\" translate=\"no\"\u003eDATA_PAYLOAD\u003c/var\u003e (optional): the event payload encoded into the media format specified by `datacontenttype` and adhering to `dataschema` when those attributes are present.\n\n\nRequest JSON body:\n\n```\n{\n\"jsonMessage\":\n \"{\\\"specversion\\\":\\\"SPEC_VERSION\\\",\n \\\"type\\\":\\\"EVENT_TYPE\\\",\n \\\"source\\\":\\\"EVENT_SOURCE\\\",\n \\\"id\\\":\\\"EVENT_ID\\\",\n \\\"datacontenttype\\\":\\\"CONTENT_TYPE\\\",\n \\\"data\\\":\\\"DATA_PAYLOAD\\\"}\"\n}\n```\n\nTo send your request, expand one of these options:\n\n#### curl (Linux, macOS, or Cloud Shell)\n\n| **Note:** The following command assumes that you have logged in to the `gcloud` CLI with your user account by running [`gcloud init`](/sdk/gcloud/reference/init) or [`gcloud auth login`](/sdk/gcloud/reference/auth/login) , or by using [Cloud Shell](/shell/docs), which automatically logs you into the `gcloud` CLI . You can check the currently active account by running [`gcloud auth list`](/sdk/gcloud/reference/auth/list).\n\n\nSave the request body in a file named `request.json`.\nRun the following command in the terminal to create or overwrite\nthis file in the current directory: \n\n```\ncat \u003e request.json \u003c\u003c 'EOF'\n{\n\"jsonMessage\":\n \"{\\\"specversion\\\":\\\"SPEC_VERSION\\\",\n \\\"type\\\":\\\"EVENT_TYPE\\\",\n \\\"source\\\":\\\"EVENT_SOURCE\\\",\n \\\"id\\\":\\\"EVENT_ID\\\",\n \\\"datacontenttype\\\":\\\"CONTENT_TYPE\\\",\n \\\"data\\\":\\\"DATA_PAYLOAD\\\"}\"\n}\nEOF\n```\n\n\nThen execute the following command to send your REST request:\n\n```\ncurl -X POST \\\n -H \"Authorization: Bearer $(gcloud auth print-access-token)\" \\\n -H \"Content-Type: application/json; charset=utf-8\" \\\n -d @request.json \\\n \"https://eventarcpublishing.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/messageBuses/BUS_NAME:publish\"\n```\n\n#### PowerShell (Windows)\n\n| **Note:** The following command assumes that you have logged in to the `gcloud` CLI with your user account by running [`gcloud init`](/sdk/gcloud/reference/init) or [`gcloud auth login`](/sdk/gcloud/reference/auth/login) . You can check the currently active account by running [`gcloud auth list`](/sdk/gcloud/reference/auth/list).\n\n\nSave the request body in a file named `request.json`.\nRun the following command in the terminal to create or overwrite\nthis file in the current directory: \n\n```\n@'\n{\n\"jsonMessage\":\n \"{\\\"specversion\\\":\\\"SPEC_VERSION\\\",\n \\\"type\\\":\\\"EVENT_TYPE\\\",\n \\\"source\\\":\\\"EVENT_SOURCE\\\",\n \\\"id\\\":\\\"EVENT_ID\\\",\n \\\"datacontenttype\\\":\\\"CONTENT_TYPE\\\",\n \\\"data\\\":\\\"DATA_PAYLOAD\\\"}\"\n}\n'@ | Out-File -FilePath request.json -Encoding utf8\n```\n\n\nThen execute the following command to send your REST request:\n\n```\n$cred = gcloud auth print-access-token\n$headers = @{ \"Authorization\" = \"Bearer $cred\" }\n\nInvoke-WebRequest `\n -Method POST `\n -Headers $headers `\n -ContentType: \"application/json; charset=utf-8\" `\n -InFile request.json `\n -Uri \"https://eventarcpublishing.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/messageBuses/BUS_NAME:publish\" | Select-Object -Expand Content\n```\n\n#### APIs Explorer (browser)\n\n\nCopy the request body and open the\n\n[method reference page](/eventarc/docs/reference/publishing/rest/v1/projects.locations.messageBuses/publish).\nThe APIs Explorer panel opens on the right side of the page.\nYou can interact with this tool to send requests.\n\nPaste the request body in this tool, complete any other required fields, and click **Execute**.\n\n\nIf successful, the server returns an HTTP `200 OK` status code and the empty response\nbody in JSON format:\n\n```\n200 OK\n\n{}\n```\n\n\u003cbr /\u003e\n\nWhat's next\n-----------\n\n- [Publish events from Google sources](/eventarc/advanced/docs/publish-events/publish-events-google-sources)\n- [Transform received events](/eventarc/advanced/docs/receive-events/transform-events)\n- [Format received events](/eventarc/advanced/docs/receive-events/configure-format-events)"]]