NewConnect Claude, Cursor, ChatGPT, and other AI agents to API Ninjas via our MCP server

How to Geocode an Address in Python

Geocoding APIUpdated May 23, 2026
To geocode an address in Python, send a GET request to the API Ninjas Geocoding endpoint with a city name. The response contains latitude and longitude coordinates:
geocode.py
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

Step 1: Get your API key

Sign up at api-ninjas.com/register.

Step 2: Make the API request

geocode.py
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

JSON
[
  {
    "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

geocode.py
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

Python
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:

Python
# 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:

Python
from requests.exceptions import HTTPError

place = geocode('Atlantis')
if place is None:
    print('No match found — try adding a country or state')

For the reverse operation (coordinates to address), use Reverse Geocoding. To find a timezone for coordinates, use Timezone.

Frequently asked questions

What address formats are supported?

The Geocoding API accepts city names with optional country (ISO 3166 two-letter code) and state. For ambiguous names like "Springfield", always pass country and state to disambiguate.

Why is the response a list?

A city name can match multiple places — for example, "Paris" exists in France and Texas. The API returns all matches; take the first or filter by country/state.

Can I do reverse geocoding (coordinates to address)?

Yes, with the separate Reverse Geocoding API. Pass lat and lon parameters to get the matching city, country, and region.

What coordinate system does the API use?

Latitude and longitude are returned in WGS 84 (decimal degrees), the same system used by GPS and Google Maps.

Is there a free tier?

Yes. Every API Ninjas account includes a free tier — no credit card required.