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

How to Get Weather Data in Python

Weather APIUpdated May 23, 2026
To get current weather data in Python, send a GET request to the API Ninjas Weather endpoint with a city name and your API key. Here's a complete working example:
weather.py
import requests

API_KEY = 'YOUR_API_KEY'
response = requests.get(
    'https://api.api-ninjas.com/v1/weather',
    params={'city': 'London'},
    headers={'X-Api-Key': API_KEY},
)
print(response.json())

Prerequisites

Step 1: Get your API key

Create a free account at api-ninjas.com/register. After signing in, copy your API key from your profile page. The free tier covers thousands of weather lookups per month — no credit card required.

Step 2: Install requests

The requests library is the standard HTTP client for Python. Install it with pip:

Shell
pip install requests

Step 3: Make the API request

The Weather endpoint accepts a city query parameter and expects your API key in theX-Api-Key header:

weather.py
import requests

API_KEY = 'YOUR_API_KEY'
response = requests.get(
    'https://api.api-ninjas.com/v1/weather',
    params={'city': 'London'},
    headers={'X-Api-Key': API_KEY},
)
print(response.json())

Step 4: Use the response

The API returns a JSON object that looks like this:

JSON
{
  "cloud_pct": 75,
  "temp": 14,
  "feels_like": 13,
  "humidity": 82,
  "min_temp": 12,
  "max_temp": 16,
  "wind_speed": 4.63,
  "wind_degrees": 240,
  "sunrise": 1717645800,
  "sunset": 1717703400
}

All temperatures are in degrees Celsius and wind speeds are in metres per second. Sunrise and sunset are Unix timestamps in UTC.

Complete example

Here's a production-ready version that reads the API key from an environment variable, uses a request timeout, and raises on non-200 responses:

weather.py
import os
import requests

API_KEY = os.environ['API_NINJAS_KEY']
URL = 'https://api.api-ninjas.com/v1/weather'


def get_weather(city: str) -> dict:
    response = requests.get(
        URL,
        params={'city': city},
        headers={'X-Api-Key': API_KEY},
        timeout=10,
    )
    response.raise_for_status()
    return response.json()


if __name__ == '__main__':
    weather = get_weather('London')
    print(f"Temperature: {weather['temp']}°C")
    print(f"Feels like:  {weather['feels_like']}°C")
    print(f"Humidity:    {weather['humidity']}%")
    print(f"Wind speed:  {weather['wind_speed']} m/s")
    print(f"Cloud cover: {weather['cloud_pct']}%")

Set the environment variable before running: export API_NINJAS_KEY=your_key_here.

Looking up weather by coordinates

If you already have latitude and longitude (for example, from a browser geolocation request or our Geocoding API), pass them directly:

Python
response = requests.get(
    'https://api.api-ninjas.com/v1/weather',
    params={'lat': 51.5074, 'lon': -0.1278},
    headers={'X-Api-Key': API_KEY},
)

Fetching weather for multiple cities

To get conditions for a list of cities, loop over them and call the function once per city:

Python
cities = ['London', 'Tokyo', 'New York', 'Sydney']

for city in cities:
    data = get_weather(city)
    print(f"{city:10} {data['temp']:>5}°C  {data['humidity']:>3}% humidity")

Error handling

Wrap the request in a try/except block to handle invalid cities, authentication failures, and rate limits:

Python
from requests.exceptions import HTTPError, RequestException

try:
    weather = get_weather('London')
except HTTPError as e:
    if e.response.status_code == 400:
        print('Invalid city name')
    elif e.response.status_code == 401:
        print('Invalid or missing API key')
    elif e.response.status_code == 429:
        print('Rate limit exceeded — slow down requests')
    else:
        print(f'HTTP error: {e}')
except RequestException as e:
    print(f'Network error: {e}')

Converting to Fahrenheit

The API returns Celsius. Convert to Fahrenheit with a one-line helper:

Python
def c_to_f(celsius: float) -> float:
    return celsius * 9 / 5 + 32

weather = get_weather('London')
print(f"{c_to_f(weather['temp']):.1f}°F")

The Weather API pairs naturally with the Geocoding API (turn an address into lat/lon) and the Air Quality API (PM2.5, ozone, and other pollutants for the same coordinates).

Frequently asked questions

Is the weather data real-time?

Yes. The Weather API returns current observations sourced from worldwide weather stations and is updated continuously.

Can I look up weather by coordinates instead of city?

Yes. Pass lat and lon query parameters instead of city — useful when you already have GPS coordinates from another API.

What temperature units does the API return?

All temperature values are returned in degrees Celsius. Convert to Fahrenheit with the formula F = C × 9/5 + 32.

Is there a free tier?

Yes. Every API Ninjas account gets a free tier that covers tens of thousands of requests per month — no credit card required.

Does the API support historical or forecast data?

The Weather endpoint returns current conditions. For other use cases, see the Air Quality API or use a dedicated forecast provider.