How to correctly use httr2 to fetch data from API

Hello,

I am trying to use the API provided by the Geocoding service to geocode addresses.

The use looks simple, according to the docs they are expecting url in this structure:

Forward Geocode: https://geocode.maps.co/search?q=address&api_key=api_key

My code is as follows:

address <- "Prince st., New York 10012"
api_key <- "my_secret_api_key"
url <- glue::glue("https://geocode.maps.co/search?q={address}&api_key={api_key}")

response <- httr2::request(url) %>%   
  httr2::req_perform()

However this does not work, I am getting this error message:

<error/httr2_failure>
Error in `httr2::req_perform()`:
! Failed to perform HTTP request.
Caused by error in `curl::curl_fetch_memory()`:
! URL rejected: Malformed input to a URL function
---
Backtrace:
    ▆
 1. ├─httr2::request(url) %>% httr2::req_perform()
 2. └─httr2::req_perform(.)
 3.   └─base::tryCatch(...)
 4.     └─base (local) tryCatchList(expr, classes, parentenv, handlers)
 5.       └─base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]])
 6.         └─value[[3L]](cond)

I tried also the older package httr, it did not work too :

httr::GET(url)

What am I doing wrong please? Just noting, that when I manually enter the url in web browser, it works fine - I get the response with geocoded address.

You have to format the address to have a valid URL. An URL can't have spaces. The comma and dot might not be valid here too.

You'll probably need something like:

address <- "Prince+st+New+York+10012"

This made it, thank you. I replaced spaces with "+" character and it works. For now it looks that commas and dots do not cause any problems...
So the final code is:

address <- "Prince st.,New York 10012" %>% str_replace_all(., " ", "+") 
api_key <- "my_api_key"
url <- glue::glue("https://geocode.maps.co/search?q={address}&api_key={api_key}")


response <- httr2::request(url) %>%  
  httr2::req_perform()

Thanks once again @arangaca

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.