Layers¶
The REST API allows you to list, create, upload, update, and delete layers in GeoServer.
Note:
You can find the official example at https://docs.geoserver.org/2.25.x/en/user/rest/layers.html
from pathlib import Path
from geoserver import GeoServer
GeoServer Connection¶
Connect to the running GeoServer instance and create a workspace and a store.
# Setup the geoserver instance
geoserver = GeoServer(
service_url="http://localhost:8080/geoserver",
username="admin",
password="geoserver",
)
Clean up the workspace and store after running the examples.
if geoserver.workspace_exists("demo"):
geoserver.delete_workspace("demo", recurse=True)
geoserver.create_workspace_from_name("demo")
'Created'
Config¶
We'll set up the configuration for the notebook:
# Directory containing sample data
DATA_DIR = Path("../tests/data")
assert DATA_DIR.exists(), f"The directory {DATA_DIR} does not exist."
Adding a Layer¶
Usually you should setup a layer using the upload_data_store method for feature-based layers or the upload_coverage_store method for raster-based layers.
file_path = DATA_DIR / "vectors" / "buildings.shp"
assert file_path.exists(), f"File not found: {file_path.as_posix()!r}"
geoserver.upload_data_store(workspace="demo", file=file_path)
'Created'
Listing all layers¶
To list all layers in GeoServer, use the get_layers method. You can specify the response format as JSON or XML (default to JSON).
geoserver.get_layers(workspace="demo")
{'layers': {'layer': [{'name': 'buildings',
'href': 'http://localhost:8080/geoserver/rest/workspaces/demo/layers/buildings.json'}]}}
xml = geoserver.get_layers(workspace="demo", format="xml")
print(xml)
<layers>
<layer>
<name>buildings</name>
<atom:link xmlns:atom="http://www.w3.org/2005/Atom" rel="alternate" href="http://localhost:8080/geoserver/rest/workspaces/demo/layers/buildings.xml" type="application/atom+xml"/>
</layer>
</layers>
Retrieve a layer¶
To retrieve a layer, use the get_layer method. You must specify the layer name.
geoserver.get_layer(name="buildings", workspace="demo")
{'layer': {'name': 'buildings',
'type': 'VECTOR',
'defaultStyle': {'name': 'polygon',
'href': 'http://localhost:8080/geoserver/rest/styles/polygon.json'},
'resource': {'@class': 'featureType',
'name': 'demo:buildings',
'href': 'http://localhost:8080/geoserver/rest/workspaces/demo/datastores/buildings/featuretypes/buildings.json'},
'attribution': {'logoWidth': 0, 'logoHeight': 0},
'dateCreated': '2024-06-12 22:31:59.747 UTC'}}
Changing a layer¶
To update a layer, use the update_layer method. You must specify the layer name and the new layer configuration.
# Using JSON format
body = {
"layer": {
"defaultStyle": {"name": "polygon"},
}
}
# Using XML format
body = """
<layer>
<defaultStyle>
<name>polygon</name>
</defaultStyle>
</layer>
"""
geoserver.update_layer(name="buildings", workspace="demo", body=body)
'Updated'