调用NASA火星车照片API任务清单端点出现Error 500求助
问题分析与解决方案
问题根源
你混淆了NASA Mars Rover Photos API的两个端点功能,并且传递了错误的参数:
- Manifest端点(
/api/v1/manifest/{rover_name})的作用是获取探测器的完整任务清单(包括所有Sol期、对应地球日期、探测器状态等),它不接受earth_date参数。 - 你错误地将Photos端点的参数(
earth_date)用到了Manifest端点上,导致服务器无法处理请求,返回500内部错误;同时服务器返回的非JSON内容触发了JSONDecodeError。 - 代码中重复传递了
api_key(URL和params里各传一次),虽然不是核心问题,但属于冗余操作。
修复后的代码示例
如果你的需求是获取指定日期的探测器任务信息或照片,可按以下方式调整:
import requests from datetime import datetime, timedelta api_key = "你的NASA API密钥" def get_rover_manifest(rover_name): """获取探测器完整任务清单""" url = f'https://api.nasa.gov/mars-photos/api/v1/manifest/{rover_name}' params = {'api_key': api_key} response = requests.get(url, params=params) print("Response received...") print(f"response: {response}") if response.status_code == 200: print("Response 200 OK") return response.json() else: print(f'ERROR: {response.status_code} - {response.reason}') # 打印服务器返回的原始内容,方便排查错误 print("服务器返回内容:", response.text) return None def get_target_date_photos(): """获取指定地球日期的探测器照片及任务信息""" target_date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d') manifest = get_rover_manifest("perseverance") if not manifest: return # 从任务清单中筛选目标日期的记录 photo_manifest = manifest['photo_manifest']['photos'] for entry in photo_manifest: if entry['earth_date'] == target_date: print(f"目标日期任务信息:Sol {entry['sol']},照片总数:{entry['total_photos']}") # 调用Photos端点获取该日期的具体照片 photos_url = "https://api.nasa.gov/mars-photos/api/v1/rovers/perseverance/photos" photos_params = { 'earth_date': target_date, 'api_key': api_key } photos_res = requests.get(photos_url, params=photos_params) if photos_res.status_code == 200: photos_data = photos_res.json() print(f"成功获取 {len(photos_data['photos'])} 张照片") return print(f"目标日期 {target_date} 无对应任务记录") get_target_date_photos()
额外建议
- 当API返回非200状态码时,优先打印响应的原始文本,能帮你快速定位服务器返回的具体错误原因。
- 调用API时,
api_key只需要传递一次(URL或params任选其一即可)。
内容的提问来源于stack exchange,提问作者Ava-HW
相关产品推荐
相关产品推荐

