Automating GeoTIFF Data Upload to GeoServer using Python


In this blog, we'll explore how to automate the process of uploading GeoTIFF files to GeoServer using Python. GeoServer is an open-source server for sharing geospatial data. The Python script provided helps in automating the upload of multiple GeoTIFF files to GeoServer.

Introduction

GeoServer is a powerful tool for sharing and editing geospatial data. Uploading GeoTIFF files to GeoServer allows for efficient storage and visualization of satellite imagery, such as NDVI data. This script automates the process of uploading multiple GeoTIFF files to GeoServer, making it convenient for managing a large number of satellite images.

Requirements

Before running the script, ensure you have the following requirements:

  • Python installed on your system.
  • requests library installed. If you haven't installed it, you can do so by running pip install requests.

Script Overview

The provided Python script automates the process of uploading GeoTIFF files to GeoServer. It iterates through a list of GeoTIFF file names and performs the following actions for each file:

  • Authentication: The script authenticates with the GeoServer using HTTP basic authentication.
  • GeoTIFF Store Creation: It creates a store for the GeoTIFF file.
  • GeoTIFF Layer Creation: It creates a layer for the GeoTIFF file within the specified workspace.
  • Style Configuration: It sets the default style for the created layer.

Now, let's dive into the code and understand each part in detail.

from requests.auth import HTTPBasicAuth
import requests
tif_files = [
"NDVI_2023-06-04",
"NDVI_2023-06-09",
"NDVI_2023-06-14",
"NDVI_2023-06-19",
"NDVI_2023-06-24",
"NDVI_2023-06-29",
"NDVI_2023-07-04",
"NDVI_2023-07-09",
"NDVI_2023-07-19",
"NDVI_2023-07-24",
"NDVI_2023-07-29",
"NDVI_2023-08-03",
"NDVI_2023-08-18",
"NDVI_2023-08-28",
"NDVI_2023-09-02",
"NDVI_2023-09-07",
"NDVI_2023-09-12",
"NDVI_2023-09-17",
"NDVI_2023-09-22",
"NDVI_2023-09-27",
"NDVI_2023-10-02",
"NDVI_2023-10-07",
"NDVI_2023-10-12",
"NDVI_2023-10-17",
"NDVI_2023-10-22",
"NDVI_2023-10-27",
"NDVI_2023-11-01"
]

for ik in tif_files:
    username = "admin"
    password = "geoserver"
    geoserver_url = "http://localhost:8080/geoserver/rest"
    workspace = "plantsat"
    store_name = ik  # Name for your GeoTIFF store
    layer_name = store_name  # Name for your GeoTIFF layer
    crs = "EPSG:4326"  # Coordinate Reference System (CRS) code
    style_name = "NDVI"  # Name of the style to be applied

    # Create a GeoTIFF store payload
    store_url = f"{geoserver_url}/workspaces/{workspace}/coveragestores"
    payload = {
        "coverageStore": {
            "name": store_name,
            "workspace": workspace,
            "type": "GeoTIFF",
            "enabled": True,
            "url": "file:data/NDVI/"+ik+".tif"  # Update with your directory path
        }
    }

    # Set up the URL for creating a layer
    layer_url = f"{geoserver_url}/workspaces/{workspace}/coveragestores/{store_name}/coverages"

    url_ready_layer = f"{geoserver_url}/workspaces/{workspace}/layers/{layer_name}.xml"

    xml_payload = f"""
    <layer>
        <defaultStyle>
            <name>{style_name}</name>
        </defaultStyle>
    </layer>
    """


    # Create a GeoTIFF layer payload
    payloadLayer = {
        "coverage": {
            "name": layer_name,
            "title": layer_name,
            "enabled": True,
            "nativeName": layer_name,
            "srs": crs,
            "metadata": {
                "time": {"enabled": True}  # Adjust metadata structure as needed
            },
            "defaultStyle": {
                "name": style_name,
            }
        }
    }


    auth = HTTPBasicAuth(username, password)
    auth_response = requests.get(geoserver_url, auth=auth)

    if auth_response.status_code == 200:
        print("Authentication successful!")

        # Create the GeoTIFF store
        store_response = requests.post(store_url, auth=auth, json=payload)

        if store_response.status_code == 201:
            print(f"GeoTIFF store '{store_name}' created successfully!")

            # Create the GeoTIFF layer
            layer_response = requests.post(layer_url, auth=auth, json=payloadLayer)

            if layer_response.status_code == 201:
                print(f"GeoTIFF layer '{layer_name}' created successfully!")
            else:
                print(f"Error creating GeoTIFF layer: {layer_response.text}")

            headers = {'Content-type': 'application/xml'}
            response = requests.put(url_ready_layer, data=xml_payload, headers=headers, auth=auth)

            if response.status_code == 200:
                print("Successfully updated layer style.")
            else:
                print("Error updating layer style:", response.status_code)
        else:
            print(f"Error creating GeoTIFF store: {store_response.text}")
    else:
        print("Authentication failed. Please check your credentials.")
        print(auth_response.text)