编写Apps Script函数调用POST API获取返回数据
编写从API获取响应的函数示例
Python 实现
使用requests库可以快速实现这类API请求函数,下面是通用请求函数和针对OTP场景的封装:
import requests def myfunction(url, body): try: # 发送POST请求,可根据API要求改为GET/PUT等 response = requests.post(url, json=body) response.raise_for_status() # 捕获HTTP状态码错误 # 解析响应,若API返回纯文本则用response.text resp_data = response.json() # 从响应数据中提取目标字段(此处假设OTP在'otp'字段下) return resp_data.get('otp') except requests.exceptions.RequestException as e: print(f"请求失败: {str(e)}") return None # 封装OTP专用函数 def otp(url, body): return myfunction(url, body) # 调用示例(替换为实际API地址和参数) # otp_result = otp("https://api.example.com/request-otp", {"user_id": "12345"}) # print(otp_result) # 输出示例: '1234'
JavaScript 实现
在浏览器或Node.js环境中,用原生fetch API实现异步请求:
async function myfunction(url, body) { try { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body) }); if (!response.ok) { throw new Error(`请求错误: ${response.status}`); } // 若API返回纯文本,替换为await response.text() const respData = await response.json(); return respData.otp; } catch (err) { console.error('请求异常:', err); return null; } } // OTP专用函数封装 async function otp(url, body) { return await myfunction(url, body); } // 调用示例 // otp("https://api.example.com/request-otp", { user_id: "12345" }) // .then(result => console.log(result)) // 输出示例: '1234' // .catch(err => console.error(err));
关键注意事项
- 根据API的实际要求调整请求方法(GET/POST等)和请求头(如需要添加授权令牌)
- 响应解析方式要匹配API返回格式:JSON用
json(),纯文本用text() - 异常处理逻辑可根据需求修改,比如抛出错误而非返回null,或者添加重试机制
内容的提问来源于stack exchange,提问作者Ahmed Khalied
相关产品推荐
相关产品推荐

