使用 Python 快速测试 Gemini API
快速测试 Gemini API
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ "contents": [{ "parts":[{"text": "Explain how AI works"}] }] }'
对应的Python测试代码
import requests import json # Replace with your actual API key api_key = "GEMINI_API_KEY" url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={api_key}" headers = { "Content-Type": "application/json" } data = { "contents": [{ "parts": [{"text": "Explain how AI works"}] }] } response = requests.post(url, headers=headers, data=json.dumps(data)) # Print the response print(response.status_code) print(json.dumps(response.json(), indent=2))
使用时替换 api_key 为实际的key
广告
脚本使用requests
库向Gemini API发送HTTP POST请求。
如果您尚未安装requests库,可以使用pip进行安装:
pip install requests