使用HTTR的POST请求

时间:2018-10-03 23:29:21

标签: r api

我正在尝试使用httr包请求数据。 Following this format:

args <- list(metrics = c(list(name = "Jobs.2018",as = "Jobs 2018")),
             constraints = list(dimensionName ="Area",
                                map = list("Latah County ID" = c(16057))))

test <- POST(url =
"https://agnitio.emsicloud.com/emsi.us.demographics/2018.3",
     add_headers(`authorization` = paste("bearer",token)),
    add_headers(`content-type` ="application/json"),
    body = toJSON(args,auto_unbox = TRUE),
    verbose())

我查找并尝试过的所有内容始终出现400 Bad Request错误。我是否需要添加一些我找不到的参数?

P.S。抱歉,这不是可重复的示例

1 个答案:

答案 0 :(得分:2)

我们将假设(很不好的事情,但对于回答来说是必要的),您是通过发出先前的token请求(如链接的API页面上所示)来获得POST的,然后正确地解码了JSON网络令牌进入token

如果做得正确,那么下一个可能的可能性就是body请求中的POST数据格式错误。

当我看一个示例API调用时:

curl --request POST \
  --url https://agnitio.emsicloud.com/emsi.us.industry/2018.3 \
  --header 'authorization: bearer <access_token>' \
  --header 'content-type: application/json' \
  --data '{ "metrics": [ { "name": "Jobs.2017", "as":"2017 Jobs" }, { "name": "Establishments.2017" } ], "constraints": [ { "dimensionName": "Area", "map": { "Latah County, ID": ["16057"] } }, { "dimensionName": "Industry", "map": { "Full Service Restaurant s": ["722511"] } } ] }'

示例JSON看起来像这样漂亮印刷:

{
  "metrics": [
    {
      "name": "Jobs.2017",
      "as": "2017 Jobs"
    },
    {
      "name": "Establishments.2017"
    }
  ],
  "constraints": [
    {
      "dimensionName": "Area",
      "map": {
        "Latah County, ID": [
          "16057"
        ]
      }
    },
    {
      "dimensionName": "Industry",
      "map": {
        "Full Service Restaurants": [
          "722511"
        ]
      }
    }
  ]
}

您的样子:

{
  "metrics": {
    "name": "Jobs.2018",
    "as": "Jobs 2018"
  },
  "constraints": {
    "dimensionName": "Area",
    "map": {
      "Latah County ID": 16057
    }
  }
}

当它需要看起来像这样时:

{
  "metrics": [
    {
      "name": "Jobs.2018",
      "as": "Jobs 2018"
    }
  ],
  "constraints": [
    {
      "dimensionName": "Area",
      "map": {
        "Latah County ID": [
          "16057"
        ]
      }
    }
  ]
}

为此,我们需要使用以下list结构:

list(
  metrics = list(
    list(
      name = jsonlite::unbox("Jobs.2018"),
      as = jsonlite::unbox("Jobs 2018")
    )),
  constraints = list(list(
    dimensionName = jsonlite::unbox("Area"),
    map = list("Latah County ID" = c("16057"))
  ))
) -> args

请特别注意,API希望map ID JSON数据元素为字符,而不是整数/数字。

现在,我们可以像这样发出POST请求了(因为它嵌入了注释,因此以易于阅读的方式隔开):

httr::POST(

  url = "https://agnitio.emsicloud.com/emsi.us.demographics/2018.3",

  httr::add_headers(
    `authorization` = sprintf("bearer %s", token)
  ),

  encode = "json", # this lets' httr do the work for you

  httr::content_type_json(), # easier than making a header yourself

  body = args,

  httr::verbose()

) -> res

应该有效,但是b / c是封闭的API,没有免费注册,我无法对其进行测试。

相关问题