javascriptrestgoogle-cloud-platformgoogle-apigoogle-translation-api

Authenticate to the Google Language API using an API key for a REST-based web application


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);
        });
}

The same results happen when using Postman:

URL: https://translation.googleapis.com/language/translate/v2
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"
                }
            }
        ]
    }
}

Why can't I make a basic request using the API key for authentication?

I did:


Solution

  • You are incorrectly passing the API key in the Authorization header of the 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);
      });