Home > Mobile >  Running a cURL in GAS
Running a cURL in GAS

Time:09-07

I am trying to use the OpenAI API in Google Apps Script but having a little trouble running the cURL. The documentation gives me this:

curl https://api.openai.com/v1/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{"model": "text-davinci-002", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 6}'

Which I wrote as this in GAS:

function myFunction() {
  var url = "https://api.openai.com/v1/completions";
  var headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ******',
    'data': {
      'model': 'text-davinci-002', 'prompt': 'Say this is a test', 'temperature': 0, 'max_tokens': 6
    }
};

var response = UrlFetchApp.fetch(url, headers);
var text = response.getResponseCode();
var data = JSON.parse(response.getContentText());
Logger.log(data);
}

where ****** is my API Key I got from my account. When I run this script, I get an error saying I didn't provide my API Key. I've double-checked and the key is correct so I'm guessing something is wrong with my formatting? TIA

CodePudding user response:

In your script, how about the following modification?

From:

  var headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ******',
    'data': {
      'model': 'text-davinci-002', 'prompt': 'Say this is a test', 'temperature': 0, 'max_tokens': 6
    }
};

var response = UrlFetchApp.fetch(url, headers);

To:

var options = {
  'contentType': 'application/json',
  'headers': { 'Authorization': 'Bearer ******' },
  'payload': JSON.stringify({ 'model': 'text-davinci-002', 'prompt': 'Say this is a test', 'temperature': 0, 'max_tokens': 6 })
};

var response = UrlFetchApp.fetch(url, options);

Note:

  • This modification supposes that your sample curl command worked fine. Please be careful about this.

Reference:

  • Related