import requests
API_KEY = 'YOUR_API_KEY'
response = requests.get(
'https://api.api-ninjas.com/v1/geocoding',
params={'city': 'San Francisco', 'country': 'US'},
headers={'X-Api-Key': API_KEY},
)
print(response.json())Prerequisites
- Python 3.7+ installed
- The
requestslibrary (pip install requests) - A free API Ninjas API key
Step 1: Get your API key
Sign up at api-ninjas.com/register.
Step 2: Make the API request
import requests
API_KEY = 'YOUR_API_KEY'
response = requests.get(
'https://api.api-ninjas.com/v1/geocoding',
params={'city': 'San Francisco', 'country': 'US'},
headers={'X-Api-Key': API_KEY},
)
print(response.json())Step 3: Use the response
[
{
"name": "San Francisco",
"latitude": 37.7790262,
"longitude": -122.4199061,
"country": "US",
"state": "California"
}
]Because place names can be ambiguous (e.g., “Paris” in France vs. Texas), the API returns a list — pass country or state to narrow the results.
Complete example with disambiguation
import os
import requests
API_KEY = os.environ['API_NINJAS_KEY']
URL = 'https://api.api-ninjas.com/v1/geocoding'
def geocode(city: str, country: str | None = None, state: str | None = None) -> dict | None:
params = {'city': city}
if country:
params['country'] = country
if state:
params['state'] = state
response = requests.get(
URL,
params=params,
headers={'X-Api-Key': API_KEY},
timeout=10,
)
response.raise_for_status()
results = response.json()
return results[0] if results else None
if __name__ == '__main__':
place = geocode('San Francisco', country='US')
if place:
print(f"{place['name']}, {place.get('state', '')}, {place['country']}")
print(f"Coordinates: {place['latitude']:.4f}, {place['longitude']:.4f}")Geocoding multiple addresses
addresses = [
('London', 'GB'),
('Paris', 'FR'),
('Tokyo', 'JP'),
('Sydney', 'AU'),
]
for city, country in addresses:
place = geocode(city, country=country)
if place:
print(f"{city:10} ({country}) {place['latitude']:>8.4f}, {place['longitude']:>9.4f}")Combining geocoding with the Weather API
Geocode an address, then pass the coordinates to the Weather API:
# Geocode an address, then look up the weather there
def weather_for_address(city: str, country: str) -> dict:
place = geocode(city, country=country)
if not place:
raise ValueError(f'Could not geocode {city}, {country}')
return requests.get(
'https://api.api-ninjas.com/v1/weather',
params={'lat': place['latitude'], 'lon': place['longitude']},
headers={'X-Api-Key': API_KEY},
timeout=10,
).json()
print(weather_for_address('Reykjavik', 'IS'))Handling missing results
If no match is found, the API returns an empty list. Always check before indexing:
from requests.exceptions import HTTPError
place = geocode('Atlantis')
if place is None:
print('No match found — try adding a country or state')Related APIs
For the reverse operation (coordinates to address), use Reverse Geocoding. To find a timezone for coordinates, use Timezone.