API Reference

Import RenewMap wind turbine data to a QGIS project.

📘

Check the API docs

https://renewmap.readme.io/reference/get-a-list-of-turbines

You will need an API key to get started.

Check the Getting Started page for instructions.

In QGIS, you can run a Python script to fetch RenewMap API data into your project.

  1. Select Plugins > Python Console and then select 📝 Show editor
  2. Create a new blank script using the ➕ icon.
  3. Paste the code below into the blank script, replacing 'YOUR_API_KEY' with your actual API key.
  4. Run the script with the ▶️ icon.
  5. The latest RenewMap data will appear in your project:
    1. A new Point layer called Wind Turbine Database with wind turbine locations and attributes

Note: the layer is stored in memory and will be lost when you close the project. Re-run the script whenever you want to get the latest data.

If you want to persist the layer to your next session, right click the layer in the Layers pane and select Make permanent. However, this permanent layer will not update with new data.

import pandas as pd
import requests
from qgis.core import QgsVectorLayer, QgsField, QgsFeature, QgsGeometry, QgsPointXY
from PyQt5.QtCore import QVariant
from typing import Dict, List
from dataclasses import dataclass

API_KEY = "YOUR_API_KEY" # Replace with your actual API key
BASE_URL = "https://api.renewmap.com.au/api/v1/turbines"
DATA_KEY = "turbines"

@dataclass
class APIConfig:
    """Configuration class for API parameters.

    Attributes:
        base_url: Base URL for the API endpoint
        limit: Number of records per request
        headers: HTTP headers for API requests
    """
    base_url: str = BASE_URL
    limit: int = 10000
    headers: Dict = None

    def __post_init__(self):
        """Initialize default headers if none provided"""
        if self.headers is None:
            self.headers = {
                "accept": "application/json",
                "Authorization": f"Bearer {API_KEY}"
            }

def fetch_data(config: APIConfig) -> pd.DataFrame:
    """Fetch data from API using pagination.

    Args:
        config: APIConfig object containing API configuration

    Returns:
        DataFrame containing all fetched data
    """
    dfs = []
    offset=0
    
    # Fetch data in chunks using pagination
    while True:
        url = f"{config.base_url}?limit={config.limit}&offset={offset}"
        response = requests.get(url, headers=config.headers)
        response.raise_for_status()
        data_dict = response.json()
        df = pd.DataFrame(data_dict[DATA_KEY])

        if df.empty:
            break # No more data available
        
        dfs.append(df)
        offset += config.limit # Increment offset for next request
    
    return pd.concat(dfs, ignore_index=True)


def create_qgis_fields(df: pd.DataFrame) -> List[QgsField]:
    """Create QGIS fields based on DataFrame columns.

    Args:
        df: Input DataFrame with project data

    Returns:
        List of QgsField objects
    """
    # Create longitude and latitude fields
    fields = [
        QgsField('Longitude', QVariant.Double),
        QgsField('Latitude', QVariant.Double)
    ]
    # Add other fields from the DataFrame
    for column in df.columns:
        if column != 'point':
            field_type = QVariant.String if df[column].dtype == 'O' else QVariant.Double
            fields.append(QgsField(column, field_type))
    
    return fields

def create_feature(row: pd.Series) -> QgsFeature:
    """Create QGIS feature from DataFrame row.

    Args:
        row: Series containing single turbine data row

    Returns:
        QgsFeature object with geometry and attributes
    """
    feature = QgsFeature()
    
    # Extract longitude and latitude from the 'point' column
    longitude, latitude = row['point']
    
    # Set geometry and attributes
    point = QgsPointXY(longitude, latitude)
    feature.setGeometry(QgsGeometry.fromPointXY(point))
    
    # Prepare attribute values
    attributes = [longitude, latitude]
    for column in df.columns:
        if column != 'point':
            value = row[column]
            if isinstance(value, list):  # Handle arrays of numbers
                value = ','.join(map(str, value))  # Convert to comma-separated string
            attributes.append(value)
    
    feature.setAttributes(attributes)
    
    return feature

def create_vector_layer(df: pd.DataFrame) -> QgsVectorLayer:
    """Create a QgsVectorLayer from a DataFrame.

    Args:
        df: Input DataFrame with turbine data

    Returns:
        QgsVectorLayer object for QGIS map display
    """
    # Create qgis layer
    layer = QgsVectorLayer("Point?crs=epsg:4326", "Wind Turbine Database", "memory")
    provider = layer.dataProvider()

    # Add fields to layer
    fields = create_qgis_fields(df)
    provider.addAttributes(fields)
    layer.updateFields()
    
    # Add features to layer
    features = [create_feature(row) for _, row in df.iterrows()]
    provider.addFeatures(features)
    layer.updateExtents()
    
    return layer

config = APIConfig()
df = fetch_data(config)
layer = create_vector_layer(df)

# Add the layer to the map
QgsProject.instance().addMapLayer(layer)