在Code by Zapier中运行Python如何正确定义输出?
在Code by Zapier的Python代码中正确输出JSON响应体的方法
你的代码存在两个核心问题,导致要么输出不符合预期,要么触发错误:
- Payload变量引用错误:你把
input_data['lastName']这类变量用引号包裹,接口收到的会是字符串"input_data['lastName']",而非实际传入的 lastName 值。 - 未按Zapier规则返回输出:Code by Zapier要求Python代码返回字典作为有效输出,仅用
print无法被识别为输出,必须通过return返回指定格式内容。
修正后的完整代码
import requests url = "https://stackoverflowpost.com" # 修正变量引用:直接使用input_data变量,不要加引号 payload = { "LeadInfo": "Lead Info", "CustomerFID": None, "RegCommunityFID": "None", "NameLast": input_data['lastName'], "NameMiddle": "None", "NameFirst": input_data['firstName'], "Title": "Mr", "NameLast2": "TEST", "NameMiddle2": "Zap", "NameFirst2": "Zap", "Title2": "", "Suffix2": "", "StreetAddress": "Zap St", "City": "Townsville", "ZipCode": "12345", "StateCode": "DE", "PhoneHome": input_data['phone'], "EmailHome": input_data['email'], "Rating": "Rating", "LeadSource": "LeadSource", "RegistrationNotes": "string", "ExternalID": "EXID", "Status": "Status", "ProspectNumber": "2", "WCCustBuyerInfo": { "ContractName": "ThisContract", "WCBuyers": [ {} ] } } headers = { 'Content-Type': 'application/json' } # 使用requests.post的json参数自动处理序列化,无需手动json.dumps response = requests.post(url, headers=headers, json=payload) # 解析响应并返回符合Zapier要求的格式 try: # 尝试将响应解析为JSON response_json = response.json() return {'response': response_json} except ValueError: # 若响应非JSON格式,返回原始文本避免报错 return {'response_text': response.text}
关键调整说明:
- 移除了手动
json.dumps操作,改用requests.post的json参数,requests会自动完成JSON序列化并适配请求头。 - 增加
try-except块处理响应解析,防止接口返回非JSON内容时触发代码错误。 - 最终返回字典格式内容,Zapier会识别该字典作为后续步骤可调用的输出数据。
内容的提问来源于stack exchange,提问作者DannyKTurns
相关产品推荐
相关产品推荐

