如何将参数传递给 REST API?

How to pass parameter to REST API?

我正在使用 R,并且有一个关于如何将参数传递给 REST API REQUEST 的问题。

我已经获得令牌并且正在使用 R,需要通过传递一些参数从 REST API 服务检索数据。这是我的代码:

library(httr)
r <- POST("https://XXXXXXXX/api/locationhazardInfo",
add_headers("Content-Type"="text/plain; charset=UTF-8",
Accept="text/plain",
"Authorization"=paste("Bearer", tok)),
body = list(
"Latitude":40.738269,
"Longitude":-74.02826,
"CountryCode":"USA",
"HazardLayers":[
{
"LayerId":"18",
"Description":""
},
{
"LayerId":"6",
"Description":""
}
],
"Distances":[
{
"Value":1,
"Unit":"miles"
}
]
)
)

tok是我从上一步得到的token。我得到了 systax 错误(似乎都是语法错误),如下所示,

非常感谢任何意见。

here is the screenshot of the error

您的 body 不是列表。 (我不认为!)。我还认为你在最后(倒数第二个)有一个 rogue ) 应该是 }

列表如下所示:

body = list(x = "A simple text string", y="Another String")

您的 body 是 JSON 编码文本。

 body = '{"a":1,"b":{}}', encode = "raw")

因此您的代码可能如下所示:

library(httr)
r <- POST(
    "https://XXXXXXXX/api/locationhazardInfo",
    add_headers(
        "Content-Type"="text/plain; charset=UTF-8",
        Accept="text/plain",
        "Authorization"=paste("Bearer", tok)
    ),
    body = '{
         "Latitude":40.738269,
         "Longitude":-74.02826,
         "CountryCode":"USA",
         "HazardLayers":[
           {
              "LayerId":"18",
              "Description":""
            },
           {
              "LayerId":"6",
              "Description":""
           }
         ],
         "Distances":[
           {
              "Value":1,
              "Unit":"miles"
           }
         ]
       }',
      encode = "raw" )

一个更新,这是至少解决了我的问题的解决方案:

rg <- POST(url, 
           # add_headers("Content-Type"="text/plain; charset=UTF-8",
           add_headers("Content-Type"="application/json",            
                       Accept="text/plain",
                       "Authorization"=paste("Bearer", tok)),
           body = '{
         "Latitude":40.738269,
         "Longitude":-74.02826,
         "CountryCode":"USA",
         "HazardLayers":[
           {
              "LayerId":"18",
              "Description":""
            },
           {
              "LayerId":"6",
              "Description":""
           }
         ],
         "Distances":[
           {
              "Value":1,
              "Unit":"miles"
           }
         ]
       }' ,
           encode = "raw"  #### , verbose()
)