Authentication overview

Authentication for HG Weather's services is a process that verifies the identity of a client attempting to access the API. It ensures that only authorized applications and users can retrieve weather data and associated services. The primary method for authenticating with HG Weather's API is through the use of an API key, which serves as a unique identifier and secret token for your application. This key must be securely transmitted with every request to any of the HG Weather endpoints.

The API key mechanism is a common authentication strategy for RESTful APIs due to its simplicity and ease of implementation. When an API key is included in a request, the HG Weather server validates the key against its records. If the key is valid and active, the request is processed; otherwise, the request is rejected, often with an HTTP 401 Unauthorized or 403 Forbidden status code. Developers are advised to handle these error codes gracefully within their applications to provide a robust user experience and appropriate debugging information.

All communication with the HG Weather API is secured using HTTPS (Hypertext Transfer Protocol Secure) and TLS (Transport Layer Security). This encryption protocol helps protect the API key and other sensitive data exchanged between your application and the HG Weather servers from eavesdropping and tampering during transit. The use of HTTPS is a standard security practice for web APIs, as detailed by the World Wide Web Consortium on web security, ensuring that data integrity and confidentiality are maintained.

Supported authentication methods

HG Weather primarily supports API key authentication. This method is suitable for most use cases, ranging from simple client-side applications to complex backend services.

Method When to Use Security Level
API Key (Query Parameter)
  • Server-side applications
  • Controlled environments where keys can be securely stored
  • Rapid prototyping and development
  • Accessing public or semi-public data (e.g., weather forecasts)
Moderate (requires careful key management)

While API keys offer a straightforward approach to authentication, their security relies heavily on how they are managed and transmitted. For instance, exposing API keys directly in client-side code (e.g., JavaScript in a web browser) can lead to unauthorized usage if the key is discovered by malicious actors. Therefore, HG Weather recommends adhering to specific security guidelines for API key deployment, which are outlined in the HG Weather API reference on authentication.

API key implementation

When making requests to the HG Weather API, your API key must be included as a query parameter in the URL. The parameter name is typically apiKey or key, as specified in the HG Weather documentation portal. For example, a request might look like this:

GET https://api.hgweather.com/v1/current?location=London&apiKey=YOUR_API_KEY

Replace YOUR_API_KEY with the actual key obtained from your HG Weather account. The consistent inclusion of this parameter in every request allows the HG Weather servers to identify and authorize your application.

Getting your credentials

To begin using the HG Weather API, you must first obtain an API key. This process involves registering an account and generating a key through the HG Weather developer dashboard. Follow these steps to get your credentials:

  1. Sign Up/Log In: Navigate to the HG Weather homepage and either sign up for a new account or log in to an existing one. Account registration is required to access the developer dashboard.
  2. Access Developer Dashboard: Once logged in, locate and access your personal developer dashboard. This area typically provides tools for managing your API subscriptions, viewing usage statistics, and generating credentials.
  3. Generate API Key: Within the dashboard, there should be a section dedicated to API Keys or Credentials. Click on an option to generate a new API key. HG Weather may allow you to create multiple keys for different projects or environments for better organization and security management.
  4. Copy Your API Key: After generation, your unique API key will be displayed. It is crucial to copy this key immediately and store it securely. The HG Weather platform typically displays the key only once upon creation, after which it cannot be retrieved directly again for security reasons. If lost, you might need to generate a new key.
  5. Review Usage Limits: While obtaining your key, it's also advisable to review the HG Weather pricing page for information regarding your specific plan's usage limits, such as the number of requests per day or month. The HG Weather documentation also describes how different subscription tiers impact API access and features.

Authenticated request example

Here's an example of how to make an authenticated request to the HG Weather API using Python, demonstrating the inclusion of the API key as a query parameter. This example fetches current weather data for London.

import requests

# Replace with your actual API key
API_KEY = "YOUR_HG_WEATHER_API_KEY"
LOCATION = "London"

# HG Weather current weather endpoint
API_URL = f"https://api.hgweather.com/v1/current?location={LOCATION}&apiKey={API_KEY}"

try:
    response = requests.get(API_URL)
    response.raise_for_status()  # Raise an exception for HTTP errors (4xx or 5xx)

    data = response.json()
    print("Current Weather for London:")
    print(f"Temperature: {data['main']['temp']}°C")
    print(f"Condition: {data['weather'][0]['description']}")

except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")
    if response.status_code == 401:
        print("Unauthorized: Check your API key.")
    elif response.status_code == 403:
        print("Forbidden: You might have exceeded your usage limits or your key is inactive.")
    else:
        print(f"Error fetching data: {response.text}")

This Python script uses the requests library to send a GET request. The API_KEY variable is concatenated directly into the URL query string. The response.raise_for_status() call is crucial for handling non-200 HTTP responses, making error detection explicit.

For Node.js, a similar approach would involve using a library like node-fetch or the built-in https module:

const fetch = require('node-fetch');

const API_KEY = 'YOUR_HG_WEATHER_API_KEY';
const LOCATION = 'London';

async function getCurrentWeather() {
    const API_URL = `https://api.hgweather.com/v1/current?location=${LOCATION}&apiKey=${API_KEY}`;

    try {
        const response = await fetch(API_URL);
        if (!response.ok) {
            if (response.status === 401) {
                throw new Error('Unauthorized: Check your API key.');
            } else if (response.status === 403) {
                throw new Error('Forbidden: Usage limits exceeded or inactive key.');
            } else {
                const errorText = await response.text();
                throw new Error(`HTTP error! Status: ${response.status}, Details: ${errorText}`);
            }
        }
        const data = await response.json();
        console.log('Current Weather for London:');
        console.log(`Temperature: ${data.main.temp}°C`);
        console.log(`Condition: ${data.weather[0].description}`);
    } catch (error) {
        console.error('An error occurred:', error.message);
    }
}

getCurrentWeather();

In both examples, error handling is included to manage potential issues such as invalid API keys, network problems, or exceeding rate limits. Consistent error handling is a key component of robust API integration, as highlighted by Google's API client library guide on error handling.

Security best practices

Securing your API key is paramount to prevent unauthorized access to your HG Weather account and services. Adhere to these best practices:

  1. Keep API Keys Confidential: Never hardcode API keys directly into public client-side code (e.g., JavaScript in browsers, mobile apps). If your application runs on a server, store the key in environment variables, a secure configuration file, or a secrets management service (e.g., AWS Secrets Manager, Google Secret Manager). For applications running client-side, consider using a proxy server to make API calls, thus keeping the key on your backend.
  2. Use HTTPS Always: All communications with the HG Weather API should occur over HTTPS. This encrypts the data in transit, protecting your API key from interception. HG Weather enforces HTTPS by default for all API endpoints.
  3. Restrict API Key Scopes/Permissions: If HG Weather offers features to limit what an API key can do (e.g., read-only access, specific endpoint access), utilize these features. This minimizes the damage if a key is compromised. Review the HG Weather security documentation for available key management options.
  4. IP Address Whitelisting: If supported, configure your API key to only accept requests originating from a list of predefined, trusted IP addresses. This adds an extra layer of security, ensuring that even if your key is stolen, it cannot be used from an unauthorized location.
  5. Monitor API Key Usage: Regularly review your API usage statistics within the HG Weather dashboard. Unusual spikes in usage could indicate a compromised key or an application error. Set up alerts if available.
  6. Regular Key Rotation: Periodically rotate your API keys, especially if you suspect a key might have been exposed or if personnel changes occur within your development team. Generate a new key, update your applications, and then revoke the old key.
  7. Error Handling: Implement robust error handling in your application to catch authentication failures (e.g., 401 Unauthorized, 403 Forbidden). This allows for quick detection of issues, including potentially compromised keys or expired credentials.
  8. Avoid Storing Keys in Version Control: Never commit API keys or other sensitive credentials directly into version control systems like Git. Use .gitignore files and environment variables to manage these secrets.

By adhering to these security best practices, developers can significantly reduce the risk of unauthorized access and ensure the integrity of their applications interacting with the HG Weather API. Consistent application of these measures aligns with general web security principles for API interactions.