> [!IMPORTANT]
> **Key Point:** You must implement Request Sync in order to submit a Cloud-to-cloud integration.

Request Sync triggers a `SYNC` request to your fulfillment for any Google user
with devices that have the specified
[`agentUserId`](https://developers.home.google.com/cloud-to-cloud/intents/sync) associated with them (which you
sent in the original SYNC request). This allows you to update users' devices
without unlinking and relinking their account. All users linked to this
identifier will receive a `SYNC` request.

You must trigger a `SYNC` request:

- If the user adds a new device.
- If the user removes an existing device.
- If the user renames an existing device.
- If you implement a new device type, trait, or add a new device feature.

## Get started

To implement Request Sync, follow these steps:

- [Enable the Google HomeGraph API](https://developers.home.google.com/cloud-to-cloud/integration/request-sync#homegraph-api)
- [Create a Service Account Key](https://developers.home.google.com/cloud-to-cloud/integration/request-sync#service-account-key)
- [Call the API](https://developers.home.google.com/cloud-to-cloud/integration/request-sync#call-api)

### Enable the Google HomeGraph API

1. In the Google Cloud Console, go to the **HomeGraph API** page.

   [Go to the HomeGraph API page](https://console.cloud.google.com/apis/api/homegraph.googleapis.com/overview)
2. Select the project that matches your smart home project ID.
3. Click **ENABLE**.

### Create a Service Account Key

Follow these instructions to generate a service account key from the Google Cloud Console:
**Note** : Ensure that you are using the correct GCP project when performing these steps. This is the project that matches your smart home project ID.

1. In the Google Cloud Console, go to the **Service accounts** page.

   [Go to the Service Accounts page](https://console.cloud.google.com/iam-admin/serviceaccounts).

   You may need to select a project before you're taken to the Service Accounts page.
2. Click **Create service account**.

3. In the **Service account name** field, enter a name.

4. In the **Service account ID** field, enter a ID.

5. In the **Service account description** field, enter a description.

6. Click **Create and continue**.

7. From the **Role** dropdown, select **Service Accounts** \> **Service Account OpenID Connect Identity Token Creator**.

8. Click **Continue**.

9. Click **Done**.

10. Select the service account you just created from the list of service accounts and
    select **Manage keys** from the
    **Actions** menu.

11. Select **Add key** \> **Create new key**.

12. For the **Key type** , select the **JSON** option.

13. Click **Create**. A JSON file that contains your key
    downloads to your computer.

For detailed instructions and information about creating service account keys, see [Create
and delete service account keys](https://cloud.google.com/iam/docs/keys-create-delete#creating) on the Google Cloud Console Help site.

### Call the API

### HTTP

The Home Graph API provides an [HTTP endpoint](https://developers.home.google.com/reference/home-graph/rest)

1. Use the downloaded service account JSON file to create a JSON Web Token (JWT). For more information, see [Authenticating Using a Service Account](https://cloud.google.com/endpoints/docs/openapi/service-account-authentication).
2. Obtain an OAuth 2.0 access token with the `https://www.googleapis.com/auth/homegraph` scope using [oauth2l](https://github.com/google/oauth2l):

```
oauth2l fetch --credentials service-account.json \
  --scope https://www.googleapis.com/auth/homegraph
```
3. Create the JSON request with the `agentUserId`. Here's a sample JSON request for Request Sync:

```console
{
  "agentUserId": "user-123"
}
```
4. Combine the Request Sync JSON and the token in your HTTP POST request to the Google Home Graph endpoint. Here's an example of how to make the request in the command line using `curl`, as a test:

```
curl -X POST -H "Authorization: Bearer ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d @request-body.json \
  "https://homegraph.googleapis.com/v1/devices:requestSync"
```

### gRPC

The Home Graph API provides a [gRPC endpoint](https://developers.home.google.com/reference/home-graph/rpc)

1. Get the [protocol buffers service definition](https://github.com/googleapis/googleapis/blob/master/google/home/graph/v1/homegraph.proto) for the Home Graph API.
2. Follow the gRPC developer documentation to generate client stubs for one of the [supported languages](https://grpc.io/docs/languages/).
3. Call the [RequestSync](https://developers.home.google.com/reference/home-graph/rpc/google.home.graph.v1#google.home.graph.v1.HomeGraphApiService.RequestSync) method.

### Node.js

The [Google APIs Node.js Client](https://www.npmjs.com/package/googleapis) provides bindings for the Home Graph API.

1. Initialize the [`google.homegraph`](https://googleapis.dev/nodejs/googleapis/latest/homegraph/classes/Homegraph.html) service using [Application Default Credentials](https://www.npmjs.com/package/googleapis#application-default-credentials).
2. Call the [`requestSync`](https://googleapis.dev/nodejs/googleapis/latest/homegraph/classes/Resource$Devices.html#requestSync) method with the [RequestSyncDevicesRequest](https://googleapis.dev/nodejs/googleapis/latest/homegraph/interfaces/Schema$RequestSyncDevicesRequest.html). It returns a `Promise` with an empty [RequestSyncDevicesResponse](https://googleapis.dev/nodejs/googleapis/latest/homegraph/interfaces/Schema$RequestSyncDevicesResponse.html).

```javascript
const homegraphClient = homegraph({
  version: 'v1',
  auth: new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/homegraph'
  })
});

const res = await homegraphClient.devices.requestSync({
  requestBody: {
    agentUserId: 'PLACEHOLDER-USER-ID',
    async: false
  }
});
    
```

### Java

The [HomeGraph API Client Library for Java](https://github.com/googleapis/google-api-java-client-services/tree/master/clients/google-api-services-homegraph/v1) provides bindings for the Home Graph API.

1. Initialize the [`HomeGraphApiService`](https://googleapis.dev/java/google-api-services-homegraph/latest/com/google/api/services/homegraph/v1/HomeGraphService.html) using [Application Default Credentials](https://github.com/googleapis/google-auth-library-java#application-default-credentials).
2. Call the [`requestSync`](https://googleapis.dev/java/google-api-services-homegraph/latest/com/google/api/services/homegraph/v1/HomeGraphService.Devices.html#requestSync-com.google.api.services.homegraph.v1.model.RequestSyncDevicesRequest--) method with the [`RequestSyncDevicesRequest`](https://googleapis.dev/java/google-api-services-homegraph/latest/com/google/api/services/homegraph/v1/model/RequestSyncDevicesRequest.html). It returns an empty [`ReportStateAndNotificationResponse`](https://googleapis.dev/java/google-api-services-homegraph/latest/com/google/api/services/homegraph/v1/model/RequestSyncDevicesResponse.html).

```java
// Get Application Default credentials.
GoogleCredentials credentials =
    GoogleCredentials.getApplicationDefault()
        .createScoped(List.of("https://www.googleapis.com/auth/homegraph"));

// Create Home Graph service client.
HomeGraphService homegraphService =
    new HomeGraphService.Builder(
            GoogleNetHttpTransport.newTrustedTransport(),
            GsonFactory.getDefaultInstance(),
            new HttpCredentialsAdapter(credentials))
        .setApplicationName("HomeGraphExample/1.0")
        .build();

// Request sync.
RequestSyncDevicesRequest request =
    new RequestSyncDevicesRequest().setAgentUserId("PLACEHOLDER-USER-ID").setAsync(false);
homegraphService.devices().requestSync(request);
    
```

> [!NOTE]
> **Note:** You should discontinue calling Request Sync upon receiving a [DISCONNECT](https://developers.home.google.com/cloud-to-cloud/intents/disconnect) intent, indicating the user has unlinked their account.

## Error responses

You may receive one of the following error responses when calling Request Sync.
These responses come in the form of HTTP status codes.

- `400 Bad Request` - The server was unable to process the request sent by the client due to **invalid syntax** . Common causes include malformed JSON or using `null` instead of "" for a string value.
- `403 Forbidden` - The server was unable to process the the request for given `agentUserId` due to an error while refreshing the token. Make sure your OAuth endpoint responds correctly to refresh token requests and check the user's account linking status.
- `404 Not Found` - The requested resource could not be found but may be available in the future. Typically, this means that the user account is not linked with Google or we received an invalid `agentUserId`. Ensure that the `agentUserId` matches the value provided in your [SYNC](https://developers.home.google.com/cloud-to-cloud/intents/sync) response, and you are properly handling [DISCONNECT](https://developers.home.google.com/cloud-to-cloud/intents/disconnect) intents.
- `429 Too Many Requests` - Maximum number of concurrent sync requests has been exceeded for the given `agentUserId`. A caller may only issue one concurrent sync request unless the `async` flag is set to true.