Reputation: 2520
Trying to access AirQuality API, very new to this and do not see simple R tutorials.
Got my username and password.
And I am interested to get LA data as a sample
api.airvisual.com/v2/city?city=Los Angeles&state=California&country=USA&key={{KEY}}
My credentials
username <- "My new free api key" (that is how they give it)
password <- "KEY"
Then I try to use some code from tutorials
library(httr)
library(jsonlite)
url <- "api.airvisual.com/v2/city?city=Los Angeles&state=California&country=USA&key={{KEY}}"
endpoint <- "city"
some_data <- GET(url, endpoint)
It gives me an error
Error in if (is_http) { : argument is of length zero
Their parameters are
Parameters
city: city's English name, can be found using the respective listing endpoint.
state: state's English name, can be found using the respective listing endpoint.
country: country's English name, can be found using the respective listing endpoint.
I am sure it is something super simple, but I never did it before, so I stumbled. Please advise.
UPD.
When I use
url <- "api.airvisual.com/v2/city?city=Los%20Angeles&state=California&country=USA&key={{KEY}}"
with %20 instead of space, it gives me an error
Error in UseMethod("as.request") : no applicable method for 'as.request' applied to an object of class "character"
Upvotes: 2
Views: 973
Reputation: 499
I don't think you need to specify endpoint. You can directly use GET as follows:
require(httr)
response = GET("https://api.airvisual.com/v2/city?city=Los%20Angeles&state=California&country=USA&key={{my_private_key}}")
If you further need to access data from the response, the code would be:
data = content(response)
data
is a list which looks like:
$status
[1] "success"
$data
$data$city
[1] "Los Angeles"
$data$state
[1] "California"
$data$country
[1] "USA"
$data$location
$data$location$type
[1] "Point"
$data$location$coordinates
$data$location$coordinates[[1]]
[1] -118.2417
$data$location$coordinates[[2]]
[1] 34.0669
$data$current
$data$current$weather
$data$current$weather$ts
[1] "2019-10-23T07:00:00.000Z"
$data$current$weather$tp
[1] 20
$data$current$weather$pr
[1] 1014
$data$current$weather$hu
[1] 52
$data$current$weather$ws
[1] 0.78
$data$current$weather$wd
[1] 345
$data$current$weather$ic
[1] "01n"
$data$current$pollution
$data$current$pollution$ts
[1] "2019-10-23T07:00:00.000Z"
$data$current$pollution$aqius
[1] 37
$data$current$pollution$mainus
[1] "p1"
$data$current$pollution$aqicn
[1] 41
$data$current$pollution$maincn
[1] "p1"
Let me know if this works.
P.S. I even tried for Los Angeles using %20 instead of the space and it works.
Upvotes: 2
Reputation: 57686
You have to provide the scheme as part of the URL:
library(httr)
GET("https://api.airvisual.com/....")
^^^^^^^^
Upvotes: 1