如何使用API密钥调用Google Cloud Translation API替代服务账号JSON
解决Google Cloud Translation API使用API密钥调用的问题
google-cloud-translate的translate_v2.Client类确实不支持直接传入API密钥作为参数,它仅接受google-auth库生成的凭证(比如你之前用的服务账号JSON对应的凭证)。不过你可以通过以下两种方式用API密钥调用Translation API:
方案1:直接调用REST接口
无需依赖客户端库,用HTTP请求工具直接发送请求即可:
import requests # 替换为你的API密钥 API_KEY = "your-api-key-here" text = "Hello world" target_lang = "zh-CN" api_url = f"https://translation.googleapis.com/language/translate/v2?key={API_KEY}" request_body = { "q": text, "target": target_lang } response = requests.post(api_url, json=request_body) response_data = response.json() # 输出翻译结果 print(response_data["data"]["translations"][0]["translatedText"])
注意:确保已在Google Cloud控制台启用Translation API,并且建议给API密钥设置使用限制(仅允许调用Translation API),提升安全性。
方案2:使用google-api-python-client库
这个官方库支持通过API密钥初始化翻译服务:
- 先安装库:
pip install google-api-python-client
- 示例代码:
from googleapiclient.discovery import build API_KEY = "your-api-key-here" # 构建翻译服务 translate_service = build('translate', 'v2', developerKey=API_KEY) # 调用翻译接口 translation_result = translate_service.translations().list( q="Hello world", target="zh-CN" ).execute() # 输出结果 print(translation_result["data"]["translations"][0]["translatedText"])
如果你一定要使用google-cloud-translate的translate_v2.Client,那确实只能依赖服务账号凭证(JSON文件),无法通过API密钥初始化该客户端。
内容的提问来源于stack exchange,提问作者anthino12
相关产品推荐
相关产品推荐

