Authentication overview

WeatherAPI.com secures access to its various weather data APIs, including real-time, forecast, and historical data, through the use of API keys. This method requires developers to obtain a unique key that must be included in every API request. The API key serves as a credential to identify the requesting application and user, enabling WeatherAPI.com to authorize access based on the user's subscription plan and track usage against their allocated request limits. This approach is common among public APIs for its simplicity and ease of implementation for both developers and API providers Cloudflare API key overview.

The API key model is suitable for applications that need straightforward access control without the complexity of token-based authentication flows like OAuth 2.0. For WeatherAPI.com, this means developers can quickly integrate weather data into applications such as small to medium-sized websites, mobile apps, or internal tools by simply appending the key to their API request URLs.

Supported authentication methods

WeatherAPI.com primarily supports API key authentication. This method involves a unique alphanumeric string that you obtain from your WeatherAPI.com account. When making a request, this key is passed as a query parameter in the URL. Other authentication mechanisms, such as OAuth 2.0 or JWT (JSON Web Tokens), are not directly supported for accessing the WeatherAPI.com endpoints WeatherAPI.com API documentation.

The table below summarizes the authentication method available for WeatherAPI.com:

Method When to Use Security Level Description
API Key (Query Parameter) Accessing all WeatherAPI.com endpoints for web, mobile, or backend applications. Moderate A unique alphanumeric string provided by WeatherAPI.com, included directly in the request URL. Easy to implement, but requires careful handling to prevent exposure.

While API keys offer a direct approach, it is critical to manage them securely to prevent unauthorized access to your WeatherAPI.com account and potential misuse of your API limits. Best practices for handling API keys include avoiding hardcoding them directly into source code and protecting them in transit.

Getting your credentials

To obtain your WeatherAPI.com API key, follow these steps:

  1. Sign Up or Log In: Navigate to the WeatherAPI.com signup page and create a new account, or log in if you already have one.
  2. Access Dashboard: Once logged in, you will be directed to your account dashboard.
  3. Locate API Key: Your unique API key will typically be displayed prominently on your dashboard. If not immediately visible, look for sections labeled "API Key", "Credentials", or "Settings". WeatherAPI.com provides your key directly on the primary dashboard view after registration WeatherAPI.com API reference.
  4. Copy Your Key: Copy the displayed API key. This is the credential you will use in all your API requests.

It is advisable to store this key securely immediately after generation. Avoid sharing your API key publicly or embedding it directly in client-side code that could be easily inspected.

Authenticated request example

Once you have obtained your API key, you can use it to make authenticated requests to WeatherAPI.com endpoints. The API key is passed as a query parameter named key in the URL. The following examples demonstrate how to make a real-time weather data request using common programming languages and cURL.

Replace YOUR_API_KEY with your actual WeatherAPI.com API key and London with your desired location.

cURL Example

curl "http://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London"

Python Example

import requests

api_key = "YOUR_API_KEY"
location = "London"
url = f"http://api.weatherapi.com/v1/current.json?key={api_key}&q={location}"

try:
    response = requests.get(url)
    response.raise_for_status() # Raise an exception for HTTP errors
    data = response.json()
    print(data)
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

Node.js Example

const fetch = require('node-fetch'); // or use axios

const apiKey = 'YOUR_API_KEY';
const location = 'London';
const url = `http://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${location}`;

async function getCurrentWeather() {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching weather data:', error);
  }
}

getCurrentWeather();

PHP Example

<?php
$apiKey = 'YOUR_API_KEY';
$location = 'London';
$url = "http://api.weatherapi.com/v1/current.json?key={$apiKey}&q={$location}";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'cURL error: ' . curl_error($ch);
} else {
    $data = json_decode($response, true);
    print_r($data);
}

curl_close($ch);
?>

Security best practices

Securing your API keys is crucial to prevent unauthorized usage and protect your WeatherAPI.com account from exceeding its rate limits or incurring unexpected charges. Adhering to these best practices will help maintain the integrity of your application and your account:

  • Do Not Hardcode API Keys: Avoid embedding API keys directly into your application's source code. Hardcoded keys can be exposed if your code repository becomes public or is compromised.
  • Use Environment Variables: For server-side applications, store your API key as an environment variable. This keeps the key out of your codebase and allows you to manage it separately for different deployment environments (Google Cloud environment variable guidance).
  • Server-Side Access Only: Whenever possible, make API requests from your backend server rather than directly from client-side code (e.g., JavaScript in a web browser or mobile app). Client-side keys are easily discoverable by anyone inspecting network requests.
  • Restrict Key Usage (if available): While WeatherAPI.com's API key system does not currently offer granular restrictions like IP address whitelisting or HTTP referrer restrictions, it is a general best practice for APIs that do. Always configure any available restrictions to limit where and how your key can be used.
  • Rotate API Keys Regularly: Periodically generate new API keys and revoke old ones. This practice reduces the window of opportunity for a compromised key to be exploited.
  • Monitor Usage: Regularly check your WeatherAPI.com dashboard for API usage patterns. Unusual spikes in requests could indicate unauthorized use of your key.
  • Secure Your Development Environment: Ensure that your local development machine and any CI/CD pipelines are secure and that API keys are not exposed in logs or build artifacts.
  • Use HTTPS: Always make requests over HTTPS to ensure that your API key and other data are encrypted during transit, protecting against eavesdropping and man-in-the-middle attacks. WeatherAPI.com exclusively uses HTTPS for its API endpoints WeatherAPI.com documentation.