oauth-2.0google-my-business-api

Error with making HTTP Call to get local posts from google business


I'm trying to call the google my business profile API to get localPosts from a place ID and then display them by embedding it as html code in a wix website. This is the method and API I'm using. In the browser's developer console I get a 401 error. I believe this has to do with the HTTP request requiring an OAuth2.0 authentication but I don't understand why I would need this as I am not accessing any user data and am grabbing public information from a google place location.

<html>
<head>
<title>Google My Business Local Posts</title>
</head>
<body>
<h1>Local Posts</h1>
<div id="localPosts"></div>

<script>
    const apiKey = 'APIKEY';

    const placeId = 'PLACEID';

    async function fetchLocalPosts() {
        try {
            const response = await fetch(`https://mybusiness.googleapis.com/v4/accounts/${apiKey}/locations/${placeId}/localPosts`, {
                headers: {
                    'Authorization': `Bearer ${apiKey}`
                }
            });

            if (response.ok) {
                const data = await response.json();

                const localPostsContainer = document.getElementById('localPosts');

                data.forEach(post => {
                    const postElement = document.createElement('div');
                    postElement.classList.add('post');

                    const titleElement = document.createElement('h2');
                    titleElement.textContent = post.title;

                    const contentElement = document.createElement('p');
                    contentElement.textContent = post.content;

                    postElement.appendChild(titleElement);
                    postElement.appendChild(contentElement);

                    localPostsContainer.appendChild(postElement);
                });
            } else {
                console.error('Request failed:', response.statusText);
            }
        } catch (error) {
            console.error('Error fetching local posts:', error);
        }
    }

    fetchLocalPosts();
</script>
</body>
</html>

Solution

  • The Business Profile APIs are not APIs that would allow you to retrieve data of anyone's location, only those locations that you own. Hence the OAuth 2.0 aspect to verify that the authenticated user also has access to those locations.