Authenticate to Google Language API using API Key for REST based web app

Authenticate to Google Language API using API Key for REST based web app

I am receiving an error 401 when trying to authenticate to Google API using an API Key.

The following is the javascript code used to make the call:

function test()
{
        const outputElement = document.getElementById('output');

        const apiUrl = 'https://translation.googleapis.com/language/translate/v2';

        const requestOptions = {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer APIKEYINSERTEDHERE',
                'x-goog-user-project': 'projectname',
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: {
                'q': 'the house is built with wood',
                'target': 'fr-CA'
            },
        };

        fetch(apiUrl, requestOptions)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                outputElement.textContent = JSON.stringify(data, null, 2);
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

Same results happen when using postman: URL: Read more Method: POST

Query Params: q=the house is built with wood target=fr-CA

Headers x-goog-user-project: projectname Authorization: Bearer APIKEYINSERTEDHERE Content-Type: application/json; charset=utf-8

Response { "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Invalid Credentials", "domain": "global", "reason": "authError", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "ACCESS_TOKEN_TYPE_UNSUPPORTED", "metadata": { "method": "google.cloud.translate.v2.TranslateService.TranslateText", "service": "translate.googleapis.com" } } ] } }

Appreciate any insights anyone has why I can't make a basic request using the API key for authentication.

Various authentication methods. Read the documentation. Debugged using POSTMAN The error messages keep changing.

Answer

You are incorrectly passing the API key in the Authorization header of google translate API. That header is only for OAuth tokens, not API keys.

You're doing this:

headers: {
  'Authorization': 'Bearer APIKEYINSERTEDHERE',
  ...
}

API keys should not go in the Authorization header.

Use the API Key as a query parameter, like below:

const apiKey = 'YOUR_API_KEY';
const apiUrl = `https://translation.googleapis.com/language/translate/v2?key=${apiKey}`;

const requestOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  },
  body: JSON.stringify({
    q: 'the house is built with wood',
    target: 'fr-CA'
  }),
};

fetch(apiUrl, requestOptions)
  .then(response => response.json())
  .then(data => {
    document.getElementById('output').textContent = JSON.stringify(data, null, 2);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles