I have a list of cities to which I'm missing a latitude and longitude data.
I found an API which after entering a city returns latitude and longitude information: https://rapidapi.com/apininjas/api/geocoding-by-api-ninjas
I´d now like to automate the process (either in Python or R), where I would input the list of cities and it would give me latitude and longitude for every city in a table.
I have this code in R to get a result from an API, but I need to get it to work automatically with the whole list of cities:
req <- request("https://geocoding-by-api-ninjas.p.rapidapi.com/") %>%
req_url_path("v1/geocoding") %>%
req_url_query(name = "New York") %>%
req_headers('X-RapidAPI-Key'='xxxxx',
'X-RapidAPI-Host'='xxx')
req %>% req_dry_run()
resp <- req %>%
req_perform()
resp %>%
resp_body_string()
Could you please help with code examples or maybe some smarter way to achieve the result?
In python it's really easy. You just need to install the library 'requests'. The code would look something like this:
import requests
cities = ["London", "Brooklyn"]
url = "https://geocoding-by-api-ninjas.p.rapidapi.com/v1/geocoding"
headers = {
"X-RapidAPI-Key": "YOU-API-KEY",
"X-RapidAPI-Host": "geocoding-by-api-ninjas.p.rapidapi.com"
}
for city in cities:
response = requests.request("GET", f"{url}?name={city}", headers=headers)
print(repsonse.text)