Weather.gov API日期参数错误:请求返回400 Bad Request求助
解决NWS API历史气象数据请求的400参数错误
问题根源
你遇到的400错误是因为NWS API的/stations/{stationId}/observations端点不识别start和end参数,该接口要求的时间参数名称是startTime和endTime。
修正后的完整代码
除了修正参数名,还需要注意两个关键细节:正确提取观测站ID,以及添加API要求的User-Agent头(否则可能被拒绝请求)。
library(httr) library(jsonlite) # NWS API基础地址 base_url <- "https://api.weather.gov" # 目标地点经纬度(示例:纽约) latitude <- "40.71" longitude <- "-74.00" # 获取该地点对应的观测站列表URL station_url <- paste0(base_url, "/points/", latitude, ",", longitude) response <- GET(station_url) station_data <- fromJSON(content(response, "text")) # 请求观测站列表并提取第一个可用站的ID(可根据需求选择其他站点) observation_stations_url <- station_data$properties$observationStations stations_response <- GET(observation_stations_url) stations_data <- fromJSON(content(stations_response, "text")) station_id <- stations_data$features[[1]]$properties$stationIdentifier # 历史数据时间范围 start_date <- "2024-10-01" end_date <- "2024-10-07" # 构造正确的历史数据请求URL(使用startTime和endTime参数) historical_url <- paste0( base_url, "/stations/", station_id, "/observations?", "startTime=", start_date, "T00:00:00Z&", "endTime=", end_date, "T23:59:59Z" ) # 添加User-Agent头(必须提供,格式:名称/联系方式) response <- GET(historical_url, add_headers("User-Agent" = "YourName/your.email@example.com")) # 检查请求状态 if (http_status(response)$category != "Success") { stop("请求失败: ", content(response, "text")) } # 解析响应数据 historical_data <- fromJSON(content(response, "text")) # 输出数据 print(historical_data) # 提取温度数据 temperature <- sapply(historical_data$features, function(x) x$properties$temperature$value)
关键注意事项
- 参数名称:严格使用
startTime和endTime作为时间范围参数,这是NWS API的规范要求。 - User-Agent头:NWS API强制要求所有请求包含该头,用于识别请求来源,避免被拦截。请替换代码中的示例信息为你自己的名称和邮箱。
- 观测站ID提取:原代码中直接提取
station_data$properties$station的方式不正确,正确路径是通过observationStations获取站点列表后选择具体站点。 - 数据分页:如果你的时间范围覆盖的观测数据较多,API会分页返回结果,需要检查响应中的
properties$next字段,循环请求直到获取所有数据。
内容的提问来源于stack exchange,提问作者coolhand
相关产品推荐
相关产品推荐

