Home > Enterprise >  How to pass parameter to REST API?
How to pass parameter to REST API?

Time:10-04

I am using R and have one question on how to pass parameter to the REST API REQUEST.

I already got the token and I am using R, and need to retrieve data from REST API service, by passing some parameters. Here is my code:

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"
}
]
)
)

The tok is the token I got from previous step. And I got the systax errors (seem all syntax errors) as shown below,

Any input is greatly appreciated.

here is the screenshot of the error

CodePudding user response:

Your body isn't a list. (I don't think!). I also think you have a rogue ) at the end (second last) which should be a }

A list would look like:

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

Your body is JSON encoded text.

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

So your code might look like this:

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" )

CodePudding user response:

An update, here is the solution at least it fixed my problem:

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()
)
  • Related