Google AppScript调用ElevenLabs API遇422错误的解决求助
解决Google AppScript调用ElevenLabs API返回422错误的问题
问题场景
在Google AppScript中集成ElevenLabs文本转语音API,期望获取返回的音频文件进行后续操作,但始终收到422状态码的错误响应。
初始错误代码
apiUrlEndPoint = "https://api.elevenlabs.io/v1/text-to-speech/Xb7hH8MSUJpSbSDYk0k2" const options = { method: 'POST', headers: { 'xi-api-key': xiApiKey 'Content-Type': 'application/json', }, body: '{"text":"This is the text to convert","model_id":"eleven_multilingual_v2","voice_settings":{"stability":1,"similarity_boost":1}}', muteHttpExceptions: true }; const response = UrlFetchApp.fetch(apiUrlEndPoint, options);
错误响应信息
Response Code: 422 Response Body: {"detail":[{"loc":["body","text"],"msg":"field required","type":"value_error.missing"}]} Request failed with status code 422
最终可行代码(2024年8月12日更新)
var apiUrlEndPoint = "https://api.elevenlabs.io/v1/text-to-speech/"+voiceId; var options = { method: 'POST', headers: { 'xi-api-key':apiKey, 'Content-Type': 'application/json', }, payload: JSON.stringify({ "text": inputText, "model_id": modelId, "voice_settings": { "stability": stability, "similarity_boost": similarity, "use_speaker_boost": speakerBoost, "style": style } }), muteHttpExceptions: true }; response = UrlFetchApp.fetch(apiUrlEndPoint, options);
关键修复说明
- Google AppScript的
UrlFetchApp.fetch()方法中,POST请求的请求体需使用payload字段,而非普通JavaScript中的body字段 - 初始代码的请求头中,
xi-api-key与Content-Type之间缺少逗号,导致格式错误 - 通过
JSON.stringify()将请求参数对象转为标准JSON字符串,确保请求体格式符合API要求
内容的提问来源于stack exchange,提问作者kenitech
相关产品推荐
相关产品推荐

