Stay organized with collectionsSave and categorize content based on your preferences.
Merchant API code sample to create a region.
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.packageshopping.merchant.samples.accounts.regions.v1;importcom.google.api.gax.core.FixedCredentialsProvider;importcom.google.auth.oauth2.GoogleCredentials;importcom.google.shopping.merchant.accounts.v1.CreateRegionRequest;importcom.google.shopping.merchant.accounts.v1.Region;importcom.google.shopping.merchant.accounts.v1.Region.PostalCodeArea;importcom.google.shopping.merchant.accounts.v1.Region.PostalCodeArea.PostalCodeRange;importcom.google.shopping.merchant.accounts.v1.RegionsServiceClient;importcom.google.shopping.merchant.accounts.v1.RegionsServiceSettings;importshopping.merchant.samples.utils.Authenticator;importshopping.merchant.samples.utils.Config;/** This class demonstrates how to create a region for a Merchant Center account. */publicclassCreateRegionSample{privatestaticStringgetParent(StringaccountId){returnString.format("accounts/%s",accountId);}publicstaticvoidcreateRegion(Configconfig,StringregionId)throwsException{// Obtains OAuth token based on the user's configuration.GoogleCredentialscredential=newAuthenticator().authenticate();// Creates service settings using the credentials retrieved above.RegionsServiceSettingsregionsServiceSettings=RegionsServiceSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create(credential)).build();// Creates parent to identify where to insert the region.Stringparent=getParent(config.getAccountId().toString());// Calls the API and catches and prints any network failures/errors.try(RegionsServiceClientregionsServiceClient=RegionsServiceClient.create(regionsServiceSettings)){CreateRegionRequestrequest=CreateRegionRequest.newBuilder().setParent(parent).setRegionId(regionId).setRegion(Region.newBuilder().setDisplayName("New York").setPostalCodeArea(PostalCodeArea.newBuilder().setRegionCode("US").addPostalCodes(PostalCodeRange.newBuilder().setBegin("10001").setEnd("10282").build()).build()).build()).build();System.out.println("Sending Create Region request");Regionresponse=regionsServiceClient.createRegion(request);System.out.println("Inserted Region Name below");// The last part of the region name will be the ID of the region.// Format: `accounts/{account}/region/{region}`System.out.println(response.getName());}catch(Exceptione){System.out.println(e);}}publicstaticvoidmain(String[]args)throwsException{Configconfig=Config.load();// The unique I
<?php/*** Copyright 2025 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\Accounts\V1\Client\RegionsServiceClient;use Google\Shopping\Merchant\Accounts\V1\CreateRegionRequest;use Google\Shopping\Merchant\Accounts\V1\Region;use Google\Shopping\Merchant\Accounts\V1\Region\PostalCodeArea;use Google\Shopping\Merchant\Accounts\V1\Region\PostalCodeArea\PostalCodeRange;/*** This class demonstrates how to create a region for a Merchant Center account.*/class CreateRegionSample{private static function getParent(string $accountId): string{return sprintf("accounts/%s", $accountId);}public static function createRegionSample(array $config, string $regionId): 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.$regionsServiceClient = new RegionsServiceClient($options);// Creates parent to identify where to insert the region.$parent = self::getParent($config['accountId']);try {// Creates the request.> $request = new CreateRegionReque>st(['parent' >= $parent,'region_id' = $r>egionId,'region' = (new Regi>on(['display_name' = 'New Yor>k','postal_code_ar>ea' = (new PostalCodeArea(['region_code' = 'US',> 'postal_codes' = [>(new PostalCodeRange(['begin' = '10001','end' = '10282']))> ]]))]))]);print "Sen>ding Create Region request\n";$response = $regionsServiceC>lient-createRegion($request);print "Inserted Region Name below\n";print $response-getName() . "\n";} catch (ApiException $e) {print $e-getMessage();}}public function callSample(): void{$config = Config::generateConfig();// Repl>ace this with
obe created.$regionId = "[INSERT REGION ID HERE]";self::createRegionSample($config, $regionId);}}$sample = new CreateRegionSample();$sample-callSample();CreateRegionSample.php
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 create a Region."""fromexamples.authenticationimportconfigurationfromexamples.authenticationimportgenerate_user_credentialsfromgoogle.shopping.merchant_accounts_v1importCreateRegionRequestfromgoogle.shopping.merchant_accounts_v1importRegionfromgoogle.shopping.merchant_accounts_v1importRegionsServiceClient_ACCOUNT=configuration.Configuration().read_merchant_info()defget_parent(account_id):returnf"accounts/{account_id}"defcreate_region(region_id_to_create):"""Creates a region for a Merchant Center account."""# Gets OAuth Credentials.credentials=generate_user_credentials.main()# Creates a client.client=RegionsServiceClient(credentials=credentials)# Creates parent to identify where to insert the region.parent=get_parent(_ACCOUNT)# Creates the request.request=CreateRegionRequest(parent=parent,region_id=region_id_to_create,region=Region(display_name="New York",postal_code_area=Region.PostalCodeArea(region_code="US",postal_codes=[Region.PostalCodeArea.PostalCodeRange(begin="10001",end="10282")],),),)# Makes the request and catches and prints any error messages.try:response=client.create_region(request=request)print("Inserted Region Name below")print(response.name)exceptRuntimeEr
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-13 UTC."],[[["\u003cp\u003eThis code provides examples in Java and Python for creating a region within a Merchant Center account using the Merchant API.\u003c/p\u003e\n"],["\u003cp\u003eThe code samples demonstrate how to set up authentication using OAuth credentials, create a \u003ccode\u003eRegionsServiceClient\u003c/code\u003e, and build a \u003ccode\u003eCreateRegionRequest\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eBoth examples showcase the creation of a region named "New York" within the US, specifically targeting postal codes ranging from "10001" to "10282".\u003c/p\u003e\n"],["\u003cp\u003eEach code sample shows how to make a request to insert a region, using a parent path that shows where the region will be inserted, and displays the name of the inserted region as a successful response.\u003c/p\u003e\n"],["\u003cp\u003eEach code sample has a \u003ccode\u003eregion_id\u003c/code\u003e value, and a \u003ccode\u003emain\u003c/code\u003e function to execute the full request.\u003c/p\u003e\n"]]],["The code samples demonstrate how to create a region for a Merchant Center account using the Merchant API. The process involves: obtaining OAuth credentials, creating a `RegionsServiceClient`, and defining a `CreateRegionRequest`. This request includes the account's parent identifier, a unique region ID, and the region details, such as display name, country code (\"US\"), and postal code ranges (e.g., 10001-10282). Finally, it makes a `createRegion` call to the API and prints the inserted region name.\n"],null,[]]