Authentication overview

The PVWatts API, provided by the National Renewable Energy Laboratory (NREL), facilitates programmatic access to its solar energy performance estimation tool. Authentication for the PVWatts API is based on a simple API key mechanism. This key is a unique identifier that grants your application permission to interact with the API, allowing NREL to monitor usage and ensure fair access to the free service. All API requests must be made over HTTPS to encrypt the transmission of your API key and other data, protecting against eavesdropping and tampering during transit, a standard practice for secure web communication as outlined by the World Wide Web Consortium's security guidelines.

The PVWatts API currently supports a single authentication method: API key. This method is suitable for applications that require straightforward access to publicly available, non-sensitive data, where the primary concern is identifying the requester for rate limiting and usage statistics rather than user-specific authorization.

Understanding the authentication process is crucial for developers integrating PVWatts into their applications. Proper handling of the API key, including secure storage and transmission, helps maintain the integrity and availability of your integration.

Supported authentication methods

PVWatts exclusively uses API keys for authenticating requests to its API. This method is common for public APIs that offer free access and primarily need to identify the application making the request rather than an individual user. The API key is passed as a query parameter in each API call.

API Key

  • Mechanism: A unique string generated by NREL, included directly in the API request URL.
  • Purpose: Identifies the calling application or developer, enabling NREL to track usage, apply rate limits, and provide access to the service.
  • Security Considerations: While convenient, API keys should be treated as sensitive credentials. Their exposure can lead to unauthorized usage of your allocated quota. It is recommended to restrict API key usage by IP address or referer where possible, though the PVWatts API primarily relies on the key itself for identification.

The table below summarizes the authentication method:

Method When to Use Security Level
API Key For all programmatic access to the PVWatts API. Suitable for server-side applications, client-side applications with proper key protection, and scripts requiring solar performance data. Moderate (relies on secure key management and HTTPS for transmission)

Getting your credentials

To access the PVWatts API, you need to obtain an API key from the NREL Developer Network. The process is free and relatively quick:

  1. Visit the NREL Developer Network: Navigate to the NREL Developer Network signup page.
  2. Register for an Account: If you don't already have one, you will need to create an account. This typically involves providing an email address, setting a password, and agreeing to the terms of service.
  3. Request an API Key: Once registered and logged in, you can request an API key for the specific NREL APIs you intend to use. For PVWatts, you'll select the relevant service. The system will generate a unique API key for your account.
  4. Retrieve Your Key: Your API key will be displayed on your developer dashboard or sent to your registered email address. Make sure to copy and store it securely.

NREL provides detailed instructions on their developer portal for managing your API keys, including options for regenerating keys if they are compromised. It is advisable to review the PVWatts API documentation for the latest information on API key usage and any service-specific requirements.

Authenticated request example

Once you have your API key, you can include it in your API requests. The PVWatts API expects the key to be passed as a query parameter named api_key. All requests must be made over HTTPS.

Here's an example of how to make an authenticated request using Python:

import requests

API_KEY = "YOUR_NREL_API_KEY"  # Replace with your actual API key
BASE_URL = "https://developer.nrel.gov/api/pvwatts/v8.json"

params = {
    "api_key": API_KEY,
    "lat": 40.7128,  # Latitude (e.g., New York City)
    "lon": -74.0060, # Longitude
    "system_capacity": 4, # System capacity in kW
    "module_type": 0,    # Standard module type
    "losses": 10,        # System losses in percent
    "array_type": 1,     # Fixed (open rack) array type
    "tilt": 20,          # Tilt angle in degrees
    "azimuth": 180,      # Azimuth angle in degrees (south-facing)
    "dataset": "tmy2"    # Weather dataset
}

try:
    response = requests.get(BASE_URL, params=params)
    response.raise_for_status()  # Raise an HTTPError for bad responses (4xx or 5xx)
    data = response.json()
    print("PVWatts API Response:")
    print(data)

    # Example: Accessing outputs
    if "outputs" in data and "ac_annual" in data["outputs"]:
        print(f"Annual AC energy production: {data['outputs']['ac_annual']} kWh")
    else:
        print("No 'outputs' or 'ac_annual' found in the response.")

except requests.exceptions.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")  # Python 3.6+
    print(f"Response content: {response.text}")
except Exception as err:
    print(f"Other error occurred: {err}")  # Python 3.6+

And an equivalent example using JavaScript (for a server-side Node.js environment, as exposing API keys client-side is discouraged):

const axios = require('axios');

const API_KEY = "YOUR_NREL_API_KEY"; // Replace with your actual API key
const BASE_URL = "https://developer.nrel.gov/api/pvwatts/v8.json";

const params = {
    api_key: API_KEY,
    lat: 34.0522,      // Latitude (e.g., Los Angeles)
    lon: -118.2437,    // Longitude
    system_capacity: 5,
    module_type: 1,
    losses: 12,
    array_type: 2,     // Fixed (roof mount)
    tilt: 25,
    azimuth: 190,
    dataset: "tmy3"
};

async function getPvwattsEstimate() {
    try {
        const response = await axios.get(BASE_URL, { params });
        console.log("PVWatts API Response:");
        console.dir(response.data, { depth: null });

        if (response.data && response.data.outputs && response.data.outputs.ac_annual) {
            console.log(`Annual AC energy production: ${response.data.outputs.ac_annual} kWh`);
        } else {
            console.log("No 'outputs' or 'ac_annual' found in the response.");
        }

    } catch (error) {
        if (error.response) {
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
            console.error(`HTTP error occurred: ${error.response.status} - ${error.response.statusText}`);
            console.error(`Response data: ${JSON.stringify(error.response.data)}`);
        } else if (error.request) {
            // The request was made but no response was received
            console.error("No response received:", error.request);
        } else {
            // Something happened in setting up the request that triggered an Error
            console.error("Error setting up request:", error.message);
        }
    }
}

pvwattsEstimate();

Security best practices

While API keys offer a straightforward authentication method, their security depends heavily on how they are managed. Adhering to best practices minimizes the risk of unauthorized access and potential misuse of your PVWatts API access:

  • Keep API Keys Confidential: Treat your API key like a password. Do not hardcode it directly into client-side code (e.g., public JavaScript files) where it can be easily extracted. Instead, use environment variables or a secure configuration management system for server-side applications. For client-side applications that must directly call the API, consider implementing a proxy server to append the API key securely.
  • Use HTTPS for All Requests: Always ensure that your API requests are made over HTTPS. This encrypts the entire communication channel, preventing your API key and other sensitive data from being intercepted by malicious actors during transmission. All modern web browsers and HTTP client libraries default to HTTPS, but it's important to verify this in your application's configuration. The IETF's HTTP/1.1 specification emphasizes the importance of secure transport for sensitive information.
  • Implement Server-Side Calls: Whenever possible, make API calls from your server-side application rather than directly from a client-side (browser-based) application. This ensures your API key remains on your secure server and is never exposed to the end-user's browser, significantly reducing the risk of compromise.
  • Avoid Storing Keys in Version Control: Never commit your API keys directly into source code repositories (e.g., Git, SVN). Use environment variables (e.g., NREL_API_KEY) or a .env file that is excluded from version control (via .gitignore).
  • Monitor Usage: Regularly check your API usage statistics on the NREL Developer Network dashboard. Unusual spikes in requests could indicate that your API key has been compromised.
  • Rotate API Keys Periodically: While not strictly enforced by NREL, it's a good security practice to periodically regenerate your API key. This limits the window of exposure if a key is ever compromised without your knowledge.
  • Apply IP Restrictions (if available): If NREL's developer portal offers the option to restrict API key usage to specific IP addresses (your server's IP), enable this feature. This adds an extra layer of security, ensuring that even if your key is stolen, it can only be used from authorized locations.
  • Error Handling and Logging: Implement robust error handling and logging for API requests. This helps identify and diagnose issues, including authentication failures, which could signal problems with your API key or unauthorized access attempts.

By following these best practices, developers can maintain a secure and reliable integration with the PVWatts API, protecting their credentials and ensuring uninterrupted access to the service.