Merchant API code sample to delete a data source.

### Java

    // Copyright 2024 Google LLC
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //
    //     https://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.

    package shopping.merchant.samples.datasources.v1;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.shopping.merchant.datasources.v1.DataSourceName;
    import com.google.shopping.merchant.datasources.v1.DataSourcesServiceClient;
    import com.google.shopping.merchant.datasources.v1.DataSourcesServiceSettings;
    import com.google.shopping.merchant.datasources.v1.DeleteDataSourceRequest;
    import shopping.merchant.samples.utils.Authenticator;
    import shopping.merchant.samples.utils.Config;

    /** This class demonstrates how to delete a datasource. */
    public class DeleteDataSourceSample {

      public static void deleteDataSource(Config config, String dataSourceId) throws Exception {
        GoogleCredentials credential = new Authenticator().authenticate();

        DataSourcesServiceSettings dataSourcesServiceSettings =
            DataSourcesServiceSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(credential))
                .build();

        String name =
            DataSourceName.newBuilder()
                .setAccount(config.getAccountId().toString())
                .setDatasource(dataSourceId)
                .build()
                .toString();

        try (DataSourcesServiceClient dataSourcesServiceClient =
            DataSourcesServiceClient.create(dataSourcesServiceSettings)) {
          DeleteDataSourceRequest request = DeleteDataSourceRequest.newBuilder().setName(name).build();

          System.out.println("Sending deleteDataSource request");
          // Delete works for any datasource type.
          // If Type "Supplemental", delete will only work if it's not linked to any primary feed.
          // If a link exists and the Type is "Supplemental", you will need to remove the supplemental
          // feed from the default and/or custom rule(s) of any primary feed(s) that references it. Then
          // retry the delete.

          dataSourcesServiceClient.deleteDataSource(request); // No response returned on success.
          System.out.println(
              "Delete successful, note that it may take a few minutes for the delete to update in"
                  + " the system.");
        }
      }

      public static void main(String[] args) throws Exception {
        Config config = Config.load();
        // An ID automatically assigned to the datasource after creation by Google.
        String dataSourceId = "1111111111"; // Replace with your datasource ID.

        deleteDataSource(config, dataSourceId);
      }
    }

### PHP

    <?php
    /**
     * Copyright 2024 Google LLC
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     https://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */

    require_once __DIR__ . '/../../../vendor/autoload.php';
    require_once __DIR__ . '/../../Authentication/Authentication.php';
    require_once __DIR__ . '/../../Authentication/Config.php';
    use Google\ApiCore\ApiException;
    use Google\Shopping\Merchant\DataSources\V1\Client\DataSourcesServiceClient;
    use Google\Shopping\Merchant\DataSources\V1\DeleteDataSourceRequest;

    /**
     * Class to demonstrate deleting a datasource.
     */
    class DeleteDataSourceSample
    {
        // ENSURE you fill in the datasource ID for the sample to work.
        private const DATASOURCE_ID = 'INSERT_DATASOURCE_ID';

        /**
         * Deletes a DataSource.
         *
         * @param int $merchantId The Merchant Center Account ID.
         * @param string $dataSourceId The data source ID.
         */
        public function deleteDataSource(int $merchantId, string $dataSourceId): void
        {
            // Gets the OAuth credentials to make the request.
            $credentials = Authentication::useServiceAccountOrTokenFile();

            // Creates options config containing credentials for the client to use.
            $options = ['credentials' => $credentials];

            // Creates a client.
            $dataSourcesServiceClient = new DataSourcesServiceClient($options);

            // Creates the data source name.
            $name = sprintf('accounts/%s/dataSources/%s', $merchantId, $dataSourceId);

            // Creates the request.
            $request = (new DeleteDataSourceRequest())
                ->setName($name);

            print('Sending deleteDataSource request' . PHP_EOL);

            // Calls the API and catches and prints any network failures/errors.
            try {
                $dataSourcesServiceClient->deleteDataSource($request);
                print('Delete successful, note that it may take a few minutes for the delete to update in the system.' . PHP_EOL);
            } catch (ApiException $ex) {
                print('Call failed with message: ' . $ex->getMessage() . PHP_EOL);
            }
        }

        // Helper to execute the sample.
        public function callSample(): void
        {
            $config = Config::generateConfig();
            // The Merchant Center Account ID.
            $merchantId = $config['accountId'];

            self::deleteDataSource($merchantId, self::DATASOURCE_ID);
        }
    }

    $sample = new DeleteDataSourceSample();
    $sample->callSample();

### Python

    # -*- coding: utf-8 -*-
    # Copyright 2024 Google LLC
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #     http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    """A module to delete a DataSource."""

    from examples.authentication import configuration
    from examples.authentication import generate_user_credentials
    from google.shopping import merchant_datasources_v1


    def delete_data_source(account_id: str, datasource_id: str):
      """Deletes the specified `DataSource` resource.

      Delete works for any datasource type.
      If Type "Supplemental", delete will only work if it's not linked to any
      primary feed. If a link exists and the Type is "Supplemental", you will need
      to remove the supplemental feed from the default and/or custom rule(s) of any
      primary feed(s) that references it. Then retry the delete.

      Args:
        account_id: The Merchant Center account ID.
        datasource_id: The ID of the data source to delete.
      """

      # Gets OAuth Credentials.
      credentials = generate_user_credentials.main()

      # Creates a client.
      client = merchant_datasources_v1.DataSourcesServiceClient(
          credentials=credentials
      )

      name = f"accounts/{account_id}/dataSources/{datasource_id}"

      # Creates the request.
      request = merchant_datasources_v1.DeleteDataSourceRequest(name=name)

      # Makes the request and catches and prints any error messages.
      try:
        # No response is returned on request.
        client.delete_data_source(request=request)
        print("Deletion successful")
      except RuntimeError as e:
        print("Deletion failed")
        print(e)
        raise


    if __name__ == "__main__":
      # Retrieves the Merchant Center account ID from the configuration file.
      merchant_account_id = configuration.Configuration().read_merchant_info()
      # ENSURE you fill in the datasource ID for the sample to
      # work.
      # An ID automatically assigned to the datasource after creation by Google.
      target_datasource = "[INSERT_DATASOURCE_HERE]"

      delete_data_source(merchant_account_id, target_datasource)