我正在尝试使用 httr 包请求数据。遵循这种格式:
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())
Run Code Online (Sandbox Code Playgroud)
我一直在400 Bad Request查找和尝试的所有内容出错。我是否需要在我没有找到的参数中添加一些内容?
PS我很抱歉这不是一个可重复的例子
我们将假设(这是一件坏事,但对于答案是必要的)您token通过发出POST链接的 API 页面上指示的先前请求获得,然后将 JSON Web 令牌正确解码为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"] } } ] }'
Run Code Online (Sandbox Code Playgroud)
该示例 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"
]
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
你的看起来像:
{
"metrics": {
"name": "Jobs.2018",
"as": "Jobs 2018"
},
"constraints": {
"dimensionName": "Area",
"map": {
"Latah County ID": 16057
}
}
}
Run Code Online (Sandbox Code Playgroud)
当它需要看起来更像这样时:
{
"metrics": [
{
"name": "Jobs.2018",
"as": "Jobs 2018"
}
],
"constraints": [
{
"dimensionName": "Area",
"map": {
"Latah County ID": [
"16057"
]
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
为此,我们需要使用以下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
Run Code Online (Sandbox Code Playgroud)
请特别注意,API 期望mapID 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
Run Code Online (Sandbox Code Playgroud)
那应该可行,但是 b/c 它是一个没有免费注册的封闭 API,我无法对其进行测试。
| 归档时间: |
|
| 查看次数: |
2021 次 |
| 最近记录: |