Sign up for email announcements to stay updated on the latest information about the GMB API.

Categories call

This standalone JavaScript sample performs OAuth 2.0 authorization. It allows the user to make a categories.list API call to fetch a list of supported business categories.

To account for regional and language preferences, categories vary by country and region. This sample uses Canadian French. Follow these requirements:

Because of the large number of business categories, the API provides the pageSize parameter and pageToken to manage returned data.

Search terms limit the number of returned categories. An empty value returns all searchTerms.

For more details on using the API and its parameters, see the Google My Business API Reference. Before you can use the API, you must add the API Key and OAuth 2.0 Client ID values from Google APIs & Services to the JavaScript source for your page.

Use the provided sample to perform OAuth 2.0 authorization and fetch a list of supported business categories:

<html>
  <head>
    <title> Google My Business API Categories Call Sample </title>
    <style>
      html, body { height: 100%; margin: 8px; }
      label {
        display: inline-block;
        float: left;
        clear: left;
        width: 128px;
        text-align: right;
        padding: 4px;
        margin: 4px;
      }
      input {
        display: inline-block;
        float: left;
        padding: 4px;
        margin: 4px;
        width: 128px;
        text-align: right;
      }
      button {
        background-color: #008CBA;
        border: none;
        color: white;
        padding: 16px 32px;
        font-size: 16px;
        margin: 8px;
      }
      #section {
        float: none;
        font-family: 'Roboto','sans-serif';
        font-weight: bold;
        font-size: large;
        display: block;
        margin: 8px;
      }
      #category-form { display: block; float: left; }
      #input-parameters { display: flex; flex-direction: column; }
      #response-area { margin: 32px; }
      #verbage { margin: 8px; }
    </style>
    <meta charset='utf-8' />
  </head>
  <body>
    <div id="section"> Google My Business API Categories Sample </div>

    <div id="verbage">
    This stand-alone JavaScript sample performs OAuth 2.0 authorization and
    allows the user to make an
    <a href="https://developers.google.com/my-business/reference/rest/v4/categories/list"> categories.list </a>
    API call to fetch a list of supported business categories.<p>
    Categories differ across regions and languages.
    Canadian French has been used in this sample as regional and language
    preferences may vary by country and region.<p>
    Regions may be input as ISO 3166-1 alpha-2 country code.<p>
    Languages maybe input input BCP 47 format.<p>
    The total number of business categories is large.
    The API provides the pageSize parameter and nextPageToken to manage
    large amounts of return data. nextPageToken is passed to subsequent
    calls to return the next pageSize block of categories up until
    totalCategoryCount is reached. <p>
    Search terms are used to limit the number of returned categories.
    An empty value returns all searchTerms.<p>
    Detailed information on using the API and parameters is available at
    <a href="https://developers.google.com/my-business/reference/rest/">
            Google My Business API Reference </a>.<p>
    Prior to use the API Key and OAuth 2.0 Client ID values from Google
    APIs & Services must be added to the JavaScript source for this page.<p>
    </div>

    <div id="section"> API Requests </div>

    <button id="authorize-button" style="display: none;"> OAuth2 Authorize </button>
    <button id="signout-button" style="display: none;"> OAuth2 Sign Out </button>
    <button id="categories-button" style="display:none;"> Get Categories </button>

    <div style='display:flex'>
    <div>
    <div id="section"> URL Parameters </div>
    <form id="category-form" style="float:left">
      <label for="regionCode"> regionCode </label> <input id="regionCode" name="regionCode" value="CA">
      <label for="languageCode"> languageCode </label> <input id="languageCode" name="languageCode" value="fr-CA">
      <label for="searchTerm"> searchTerm </label> <input id="searchTerm" name="searchTerm" value="restaurant">
      <label for="pageSize"> pageSize </label> <input id="pageSize" name="pageSize" value="10">
      <label for="pageToken"> pageToken </label> <input id="pageToken" name="pageToken" value="">
    </form>
    </div>
    </div>

    <div id="section"> API Request/Response </div>
    <pre id="response-area"> </pre>

    <script type="text/javascript">

      // Enter an API key from the Google API Console:
      //   https://console.developers.google.com/apis/credentials
      var apiKey = 'YOUR_API_KEY_HERE';

      // Enter a client ID for a web application from the Google API Console:
      //   https://console.developers.google.com/apis/credentials?project=_
      // In your API Console project, add a JavaScript origin that corresponds
      // to the domain where you will be running the script.
      var clientId = 'YOUR_CLIENT_ID_HERE';

      // Use the latest Google My Business API version
      var gmb_api_version = 'https://mybusiness.googleapis.com/v4';

      // One or more authorization scopes. Additional scopes may be desired if
      // multiple APIs are used. Refer to the documentation for the API
      // or https://developers.google.com/people/v1/how-tos/authorizing
      // for details. At a minimum include the Google My Business authorization scope.
      var scopes = 'https://www.googleapis.com/auth/business.manage';

      var authorizeButton = document.getElementById('authorize-button');
      var signoutButton = document.getElementById('signout-button');
      var categoriesButton = document.getElementById('categories-button');

      function handleClientLoad() {
        // Load the API client and auth2 library
        gapi.load('client:auth2', initClient);
      }

      function initClient() {
        gapi.client.init({
            apiKey: apiKey,
            clientId: clientId,
            scope: scopes
        }).then(function () {
          // Listen for sign-in state changes.
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());

          authorizeButton.onclick = handleAuthClick;
          signoutButton.onclick = handleSignoutClick;
          categoriesButton.onclick = handleCategoriesClick;
        });
      }

      function updateSigninStatus(isSignedIn) {
        if (isSignedIn) {
          authorizeButton.style.display = 'none';
          signoutButton.style.display = 'inline-block';
          categoriesButton.style.display = 'inline-block';
        } else {
          authorizeButton.style.display = 'inline-block';
          signoutButton.style.display = 'none';
          categoriesButton.style.display = 'none';
        }
      }

      function handleAuthClick(event) {
        gapi.auth2.getAuthInstance().signIn();
      }

      function handleSignoutClick(event) {
        gapi.auth2.getAuthInstance().signOut();
      }

      function xhrGet(url) {

        // visually get a sense of response time
        document.getElementById('response-area').innerHTML = '';

          return new Promise(function(resolve, reject) {
          var req = new XMLHttpRequest();
          var user = gapi.auth2.getAuthInstance().currentUser.get();
          var oauthToken = user.getAuthResponse().access_token;

          req.responseType = 'json';
          req.open('GET', url);

          // Authorize this request to the API by adding the bearer token
          // to the HTTP Request Headers in the authorization field
          req.setRequestHeader('Authorization', 'Bearer ' + oauthToken);

          req.onload = function() {
            if (req.status == 200) {
              resolve(req);
            } else {
              reject(req);
            }
          }

          req.onerror = function() {
            reject(Error(
              "Network Error: DNS, TLS or CORS preflight may have failed.<br>"
            + "Confirm that the API project permissions, the request URL "
            + "format and HTTP headers are set appropriately.<br>"
            + "For more information on CORS preflight failures please see: "
            + "https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request"));
          }

          req.send();
        });
      }

      function htmlifyResponse(xhr) {
        var p = document.createElement('p');

        document.getElementById('response-area').style.background = '';
        document.getElementById('response-area').style.display = 'inherit';

        p.appendChild(document.createTextNode('Request URL:  '));
        p.appendChild(document.createTextNode(xhr.responseURL));
        p.appendChild(document.createElement('br'));
        p.appendChild(document.createTextNode('Status Code:  ' + xhr.status));
        p.appendChild(document.createElement('br'));
        p.appendChild(document.createTextNode('Response Body:'));
        p.appendChild(document.createElement('br'));
        p.appendChild(document.createTextNode(JSON.stringify(
                        xhr.response, undefined, 2)));
        document.getElementById('response-area').appendChild(p);
      }

      function htmlifyError(xhr) {
        htmlifyResponse(xhr);
        document.getElementById('response-area').style.background = '#F7BD67';
      }

      function handleCategoriesClick(event) {
        var formData = new FormData(document.getElementById('category-form'));
        var url = gmb_api_version + '/categories'
                    + '?regionCode=' + formData.get('regionCode')
                    + '&languageCode=' + formData.get('languageCode')
                    + '&searchTerm=' + formData.get('searchTerm')
                    + '&pageSize=' + formData.get('pageSize')
                    + '&pageToken=' + formData.get('pageToken');

        // Make an XMLHttpRequest, outputting HTML to our response area
        xhrGet(url)
          .then(htmlifyResponse)
          .catch(htmlifyError);
      }

    </script>

    <script async defer src="https://apis.google.com/js/api.js"
      onload="this.onload=function(){};handleClientLoad()"
      onreadystatechange="if (this.readyState === 'complete') this.onload()">
    </script>

  </body>
</html>