Gemini Error with appscript integration

Am building a Google chat integration with Gemini application api. I see below error. Could someone provide some pointers where the actual issue in the below code .

Code Request :slight_smile:


  const options = {
    "method": "post",
    "payload": {
      "contents": [{
        "role": "user",
        "parts": [{
          "text": "Provide a Google chat reply for the message\n" + userMessage
        }]
      }],
      "safetySettings": [{
        "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        "threshold": "BLOCK_NONE"
      },
      {
        "category": "HARM_CATEGORY_HATE_SPEECH",
        "threshold": "BLOCK_NONE"
      },
      {
        "category": "HARM_CATEGORY_HARASSMENT",
        "threshold": "BLOCK_NONE"
      },
      {
        "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
        "threshold": "BLOCK_NONE"
      }]
    },
    "headers": {
      "Content-Type": "application/json",
      "Authorization": "Bearer " + apiKey
    },
     muteHttpExceptions: false 
  };
 const response = UrlFetchApp.fetch(`https://generativelanguage.googleapis.com/v1/models/${modelId}:generateContent`, options);
    if (response.getResponseCode() === 200) {
      const data = JSON.parse(response.getContentText());
      const geminiResponse = data.candidates[0].content.parts[0].text;
      const widgets = [{
        textParagraph: {
          text: 'Hello ' + name + '\n\n' + geminiResponse
        }
      }];
      // Use the widgets for your chat reply logic (e.g., displaying in a card)
      console.log("Gemini Response:", widgets);

Api response ::

Error: { [Exception: Request failed for https://generativelanguage.googleapis.com returned code 401. Truncated server response: {
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or othe... (use muteHttpExceptions option to examine full response)] name: 'Exception' }

The big problem is with this line:

Assuming this is an AI Studio API Key - it isn’t sent in the “Authorization” HTTP header.

  • Typically, this is done using a “key” query parameter with the URL. So the URL would be more like https://generativelanguage.googleapis.com/v1/models/${modelId}:generateContent?key=${apiKey}
  • If you wish to send it in a header, you can use the “X-Goog-Api-Key” header (without the “Bearer” text).