Using GeoServer REST API with Python

As many of you will know GeoServer has a built-in RESTful interface for interacting with your GeoServer instance. If you are using REST via Python there is a useful but by the developers own admission not well documented library called gsconfig that simplifies the process.


I have been using this library recently to publish layers from PostGIS and had to do a bit of digging to uncover some parts of the process, so I wanted to document the process I went through in case anyone else is looking to do the same thing.

1. Install gsconfig

This is well covered in the documentation here

2. Connect to your GeoServer catalogue

The first step once you have gsconfig installed is to make a connection to your GeoServer instance

cat = Catalog('http://localhost:8080/geoserver/rest')
3. Create a new workspace to publish your layers

Now create a new workspace if you don’t have one already setup

ws = cat.create_workspace('newWorkspaceName','')
4. Create a new store from your PostGIS database

The next step is to create a new feature store pointing to an existing PostGIS database. A tip here is if the layer you want to publish is in a schema other than ‘public’ make sure you supply the schema in the connection string. I found that when I didn’t GeoServer wouldn’t pick up the projection of my layer when I was publishing it.

ds = cat.create_datastore('newDatastoreName','newWorkspaceName')
ds.connection_parameters.update(host='localhost', port='5432', database='postgis', user='postgres', passwd='password', dbtype='postgis', schema='postgis')
5. Publish a layer using the new workspace and store

Now use the workspace and feature store you just created to publish a layer from PostGIS

ft = cat.publish_featuretype('newLayerName', ds, 'EPSG:4326', srs='EPSG:4326')

The first epsg code is the native projection of the layer and the second is the published projection. They don’t have to be the same, but in this case the layer is already on the projection I wanted to publish.

6. Create a new style from an SLD

If you want to apply a different style to your published layer you can create a new style from SLD, otherwise skip this step and GeoServer will apply the default style.

with open(path_to_sld_file) as f:
   cat.create_style('newStyle',, overwrite=True)

Setting overwrite=true will overwrite any existing SLDs with the same name.

7. Apply the new style to your layer

Apply your newly created style to your new layer.

layer = cat.get_layer('newLayerName')
layer.default_style = newStyle

gsconfig is a great library and with a bit of effort to figure it out it abstracts away a lot of the work involved in making REST requests to GeoServer.

Contact us through Facebook, Twitter or LinkedIn.


Comments are closed.