Zum Hauptinhalt springen

Creating GeoPandas data frames from WFS urls

Today I learned that you can create a geopoandas data frame object from an WFS request url. Thanks to htenkanen, who gave this detailed stackoverflow answer. Now I know, that if I combine a dict with the relevant WFS params, build a Request object from requests lib, I can compute an well formed GET url to retrieve all features of the WFS.

Since I am living in Germany I tried to find some governmental open-data WFS and applied the answer that htenkanen gave, to its configuration. With the following code, you get all administrative boundaries (de: Verwaltungseinheit) of the federal state Hesse (de: Hessen) as data frame. I highlighted the lines that I needed to change to get it working.

Line 9 needed a explicit version parameter and line 18 needed typeNames instead of typeName.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import geopandas as gpd
from requests import Request
from owslib.wfs import WebFeatureService

# URL for WFS backend
url = 'https://www.gds.hessen.de/wfs2/aaa-suite/cgi-bin/alkis/vereinf/wfs'

# Initialize
wfs = WebFeatureService(url=url, version="2.0.0")

# Fetch the last available layer
layer_name = list(wfs.contents)[-1]

# Specify the parameters for fetching the data
# Count: specificies amount of rows to return (e.g. 10000 or 100)
# startIndex: specifies at which offset to start returning rows
params = dict(service='WFS', version="2.0.0", request='GetFeature',
      typeNames=layer_name, count=100, startIndex=0)

# Parse the URL with parameters
wfs_request_url = Request('GET', url, params=params).prepare().url

# Read data from URL
data = gpd.read_file(wfs_request_url)

Note

To adjust the request dictionary to work with your particular WFS instance, it’s easier to paste the wfs_request_url into a browser bar (or CLI curl) and maybe get an verbose error message by the called service itself.