首页 > 解决方案 > 所需响应中没有数据时的 HTTR 警告

问题描述

我正在使用httr. 我正在使用的 API 没有people当年的内容,但会返回版权数据。当我使用时,httr::GET我仍然会收到 200 状态代码,因为有响应。

响应应该有类似于 2019 的数据。如何使用httr抛出错误?是否有类似httr::warn_for_status可用的警告?

有效并返回人员的请求示例与无效的请求示例

library(httr)

data <- GET("https://statsapi.mlb.com/api/v1/sports/1/players?season=2019")
# response with data in content.  I'll spare everyone the 1,410 rows in the JSON Response
str(content(data, type= "application/json"), list.len = 2)
#> List of 2
#>  $ copyright: chr "Copyright 2020 MLB Advanced Media, L.P.  Use of any content on this page acknowledges agreement to the terms po"| __truncated__
#>  $ people   :List of 1410
#>   ..$ :List of 36
#>   .. ..$ id              : int 472551
#>   .. ..$ fullName        : chr "Fernando Abad"
#>   .. .. [list output truncated]
#>   ..$ :List of 35
#>   .. ..$ id              : int 650556
#>   .. ..$ fullName        : chr "Bryan Abreu"
#>   .. .. [list output truncated]
#>   .. [list output truncated]

no_data <- GET("https://statsapi.mlb.com/api/v1/sports/1/players?season=2020")

str(content(no_data, type= "application/json"))
#> List of 2
#>  $ copyright: chr "Copyright 2020 MLB Advanced Media, L.P.  Use of any content on this page acknowledges agreement to the terms po"| __truncated__
#>  $ people   : list()

我使用的替代方法是解析数据,然后使用nrow(df) < 1. 一定有更好的方法。

标签: rtidyversehttr

解决方案


推荐阅读