Google 使用 API cURL 请求并获取 422 响应代码的脚本

Google Script using an API cURL Request and getting a 422 Response code

我的编码知识很不稳定,因为我没有按顺序学习。 现在,我正在尝试发送一个 cURL 请求,文档是:

卷曲 https://api.at356.com/studio/v1/sd-large/complete
-H 'Content-Type: application/json'
-H 'Authorization: Bearer YOUR_API_KEY'
-X POST
-d '{"提示": "生活就像", “结果数”:1, }'

这是代码

function searchFor(query) {
  // Base URL to access 
  var urlTemplate = "https://api.at356.com/studio/v1/sd-large/complete "
  // Script-specific credentials & search engine
  var ApiKey = "shwMCMgEviwfz6X7Rvbtna6";

  var prompt = {
    "prompt": query,
    "numResults": 1,
  }
  // Build custom cURL  
  var cURL = {
      'method': 'POST',
      "headers":{
        "Content-type": "application/json",
        "Authorization": ApiKey,
      },
      
      prompt,
      
   
    
    "muteHttpExceptions": true,
        "followRedirects": true,
        "validateHttpsCertificates": true
  };

  // Perform Request
  //Logger.log( UrlFetchApp.getRequest(urlTemplate, params) );  // Log query to be sent
  var response = UrlFetchApp.fetch(urlTemplate, cURL,);
  var respCode = response.getResponseCode();

  if (respCode !== 200) {
    throw new Error("Error " + respCode + " " + response.getContentText());
  } else {
    // Successful search, log & return results
    var result = JSON.parse(response.getContentText());
    Logger.log("Obtained %s search results in %s seconds.",
      result.searchInformation.formattedTotalResults,
      result.searchInformation.formattedSearchTime);


    return result;
  }

}

任何人都可以告诉我我做错了什么以及如何解决它

我相信你的目标如下。

  • 您想将以下 curl 命令转换为 Google Apps 脚本。

      curl https://api.at356.com/studio/v1/sd-large/complete \
      -H 'Content-Type: application/json' \
      -H 'Authorization: Bearer YOUR_API_KEY' \
      -X POST \
      -d '{"prompt": "Life is like", "numResults": 1, }'
    
  • 您已经确认您的 curl 命令可以正常工作。

修改后的脚本:

var query = "###"; // Please set the value.
var ApiKey = "###"; // Please set your API key.

var url = "https://api.at356.com/studio/v1/sd-large/complete";
var prompt = {
  "prompt": query,
  "numResults": 1,
};
var params = {
  "method": "POST",
  "headers": { "Authorization": "Bearer " + ApiKey },
  "contentType": "application/json",
  "payload": JSON.stringify(prompt),
  "muteHttpExceptions": true,
};
var response = UrlFetchApp.fetch(url, params);
console.log(response.getContentText());

注:

  • 根据您的示例 curl 命令,Authorization 类似于 -H 'Authorization: Bearer YOUR_API_KEY'。所以我修改为"headers": { "Authorization": "Bearer " + ApiKey }。如果您的实际 API 密钥类似于 Bearer ###,请将其修改为 "headers": { "Authorization": ApiKey }

参考: