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
- Python 3.7+ installed
- The
requestslibrary (pip install requests) - A free API Ninjas API key
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:
pip install requestsStep 3: Make the API request
The Weather endpoint accepts a city query parameter and expects your API key in theX-Api-Key header:
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:
{
"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:
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:
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:
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:
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:
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")Related APIs
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).