API documentation

Top level code documentation. Follow the links in each section for module/class member information.

API

Root level code of pygeoapi, parsing content provided by web framework. Returns content from plugins and sets responses.

class pygeoapi.api.API(config)[source]

API object

__init__(config)[source]

constructor

Parameters

config – configuration dict

Returns

pygeoapi.API instance

__weakref__

list of weak references to the object (if defined)

delete_process_job(process_id, job_id) → Tuple[dict, int, str][source]

Delete a process job

Parameters
  • process_id – process identifier

  • job_id – job identifier

Returns

tuple of headers, status code, content

get_exception(status, headers, format_, code, description) → Tuple[dict, int, str][source]

Exception handler

Parameters
  • status – HTTP status code

  • headers – dict of HTTP response headers

  • format – format string

  • code – OGC API exception code

  • description – OGC API exception code

Returns

tuple of headers, status, and message

get_format_exception(request) → Tuple[dict, int, str][source]

Returns a format exception.

Parameters

request – An APIRequest instance.

Returns

tuple of (headers, status, message)

class pygeoapi.api.APIRequest(request, supported_locales)[source]

Transforms an incoming server-specific Request into an object with some generic helper methods and properties.

Note

Typically, this instance is created automatically by the pre_process() decorator. Every API method that has been routed to a REST endpoint should be decorated by the pre_process() function. Therefore, all routed API methods should at least have 1 argument that holds the (transformed) request.

The following example API method will:

  • transform the incoming Flask/Starlette Request into an APIRequest using the pre_process() decorator;

  • call is_valid() to check if the incoming request was valid, i.e. that the user requested a valid output format or no format at all (which means the default format);

  • call API.get_format_exception() if the requested format was invalid;

  • create a dict with the appropriate Content-Type header for the requested format and a Content-Language header if any specific language was requested.

@pre_process
def example_method(self, request: Union[APIRequest, Any], custom_arg):
   if not request.is_valid():
      return self.get_format_exception(request)

   headers = request.get_response_headers()

   # generate response_body here

   return headers, 200, response_body

The following example API method is similar as the one above, but will also allow the user to request a non-standard format (e.g. f=xml). If xml was requested, we set the Content-Type ourselves. For the standard formats, the APIRequest object sets the Content-Type.

@pre_process
def example_method(self, request: Union[APIRequest, Any], custom_arg):
   if not request.is_valid(['xml']):
      return self.get_format_exception(request)

   content_type = 'application/xml' if request.format == 'xml' else None
   headers = request.get_response_headers(content_type)

   # generate response_body here

   return headers, 200, response_body

Note that you don’t have to call is_valid(), but that you can also perform a custom check on the requested output format by looking at the format property. Other query parameters are available through the params property as a dict. The request body is available through the data property.

Note

If the request data (body) is important, always create a new APIRequest instance using the with_data() factory method. The pre_process() decorator will use this automatically.

Parameters
  • request – The web platform specific Request instance.

  • supported_locales – List or set of supported Locale instances.

__init__(request, supported_locales)[source]

Initialize self. See help(type(self)) for accurate signature.

__weakref__

list of weak references to the object (if defined)

_get_format(headers) → Optional[str][source]

Get Request format type from query parameters or headers.

Parameters

headers – Dict of Request headers

Returns

format value or None if not found/specified

_get_locale(headers, supported_locales)[source]

Detects locale from “lang=<language>” param or Accept-Language header. Returns a tuple of (raw, locale) if found in params or headers. Returns a tuple of (raw default, default locale) if not found.

Parameters
  • headers – A dict with Request headers

  • supported_locales – List or set of supported Locale instances

Returns

A tuple of (str, Locale)

static _get_params(request)[source]

Extracts the query parameters from the Request object.

Parameters

request – A Flask or Starlette Request instance

Returns

ImmutableMultiDict or empty dict

property data

Returns the additional data send with the Request (bytes)

property format

Returns the content type format from the request query parameters or headers.

Returns

Format name or None

get_linkrel(format_: str)str[source]

Returns the hyperlink relationship (rel) attribute value for the given API format string.

The string is compared against the request format and if it matches, the value ‘self’ is returned. Otherwise, ‘alternate’ is returned. However, if format_ is ‘json’ and no request format was found, the relationship ‘self’ is returned as well (JSON is the default).

Parameters

format – The format to compare the request format against.

Returns

A string ‘self’ or ‘alternate’.

get_request_headers(headers)dict[source]

Obtains and returns a dictionary with Request object headers.

This method adds the headers of the original request and makes them available to the API object.

Returns

A header dict

get_response_headers(force_lang: babel.core.Locale = None, force_type: str = None)dict[source]

Prepares and returns a dictionary with Response object headers.

This method always adds a ‘Content-Language’ header, where the value is determined by the ‘lang’ query parameter or ‘Accept-Language’ header from the request. If no language was requested, the default pygeoapi language is used, unless a force_lang override was specified (see notes below).

A ‘Content-Type’ header is also always added to the response. If the user does not specify force_type, the header is based on the format APIRequest property. If that is invalid, the default MIME type application/json is used.

..note:: If a force_lang override is applied, that language

is always set as the ‘Content-Language’, regardless of a ‘lang’ query parameter or ‘Accept-Language’ header. If an API response always needs to be in the same language, ‘force_lang’ should be set to that language.

Parameters
  • force_lang – An optional Content-Language header override.

  • force_type – An optional Content-Type header override.

Returns

A header dict

property headers

Returns the dictionary of the headers from the request.

Returns

Request headers dictionary

is_valid(additional_formats=None)bool[source]
Returns True if:
  • the format is not set (None)

  • the requested format is supported

  • the requested format exists in a list if additional formats

Note

Format names are matched in a case-insensitive manner.

Parameters

additional_formats – Optional additional supported formats list

Returns

bool

property locale

Returns the user-defined locale from the request object. If no locale has been defined or if it is invalid, the default server locale is returned.

Note

The locale here determines the language in which pygeoapi should return its responses. This may not be the language that the user requested. It may also not be the language that is supported by a collection provider, for example. For this reason, you should pass the raw_locale property to the l10n.get_plugin_locale() function, so that the best match for the provider can be determined.

Returns

babel.core.Locale

property params

Returns the Request query parameters dict

property path_info

Returns the web server request path info part

property raw_locale

Returns the raw locale string from the Request object. If no “lang” query parameter or Accept-Language header was found, None is returned. Pass this value to the l10n.get_plugin_locale() function to let the provider determine a best match for the locale, which may be different from the locale used by pygeoapi’s UI.

Returns

a locale string or None

classmethod with_data(request, supported_locales)pygeoapi.api.APIRequest[source]

Factory class method to create an APIRequest instance with data.

If the request body is required, an APIRequest should always be instantiated using this class method. The reason for this is, that the Starlette request body needs to be awaited (async), which cannot be achieved in the __init__() method of the APIRequest. However, APIRequest can still be initialized using __init__(), but then the data property value will always be empty.

Parameters
  • request – The web platform specific Request instance.

  • supported_locales – List or set of supported Locale instances.

Returns

An APIRequest instance with data.

pygeoapi.api.FORMAT_TYPES = {'html': 'text/html', 'json': 'application/json', 'jsonld': 'application/ld+json'}

Formats allowed for ?f= requests (order matters for complex MIME types)

pygeoapi.api.HEADERS = {'Content-Type': 'application/json', 'X-Powered-By': 'pygeoapi 0.12.dev0'}

Return headers for requests (e.g:X-Powered-By)

pygeoapi.api.SYSTEM_LOCALE = Locale('en', territory='US')

Locale used for system responses (e.g. exceptions)

pygeoapi.api.pre_process(func)[source]

Decorator that transforms an incoming Request instance specific to the web framework (i.e. Flask or Starlette) into a generic APIRequest instance.

Parameters

func – decorated function

Returns

func

pygeoapi.api.validate_bbox(value=None)list[source]

Helper function to validate bbox parameter

Parameters

valuelist of minx, miny, maxx, maxy

Returns

bbox as list of float values

pygeoapi.api.validate_datetime(resource_def, datetime_=None)str[source]

Helper function to validate temporal parameter

Parameters
  • resource_defdict of configuration resource definition

  • datetimestr of datetime parameter

Returns

str of datetime input, if valid

flask_app

Flask module providing the route paths to the api

pygeoapi.flask_app.collection_coverage(collection_id)[source]

OGC API - Coverages coverage endpoint

Parameters

collection_id – collection identifier

Returns

HTTP response

pygeoapi.flask_app.collection_coverage_domainset(collection_id)[source]

OGC API - Coverages coverage domainset endpoint

Parameters

collection_id – collection identifier

Returns

HTTP response

pygeoapi.flask_app.collection_coverage_rangetype(collection_id)[source]

OGC API - Coverages coverage rangetype endpoint

Parameters

collection_id – collection identifier

Returns

HTTP response

pygeoapi.flask_app.collection_items(collection_id, item_id=None)[source]

OGC API collections items endpoint

Parameters
  • collection_id – collection identifier

  • item_id – item identifier

Returns

HTTP response

pygeoapi.flask_app.collection_queryables(collection_id=None)[source]

OGC API collections querybles endpoint

Parameters

collection_id – collection identifier

Returns

HTTP response

pygeoapi.flask_app.collections(collection_id=None)[source]

OGC API collections endpoint

Parameters

collection_id – collection identifier

Returns

HTTP response

pygeoapi.flask_app.conformance()[source]

OGC API conformance endpoint

Returns

HTTP response

pygeoapi.flask_app.execute_process_jobs(process_id)[source]

OGC API - Processes execution endpoint

Parameters

process_id – process identifier

Returns

HTTP response

pygeoapi.flask_app.get_collection_edr_query(collection_id, instance_id=None)[source]

OGC EDR API endpoints

Parameters
  • collection_id – collection identifier

  • instance_id – instance identifier

Returns

HTTP response

pygeoapi.flask_app.get_collection_tiles(collection_id=None)[source]

OGC open api collections tiles access point

Parameters

collection_id – collection identifier

Returns

HTTP response

pygeoapi.flask_app.get_collection_tiles_data(collection_id=None, tileMatrixSetId=None, tileMatrix=None, tileRow=None, tileCol=None)[source]

OGC open api collection tiles service data

Parameters
  • collection_id – collection identifier

  • tileMatrixSetId – identifier of tile matrix set

  • tileMatrix – identifier of {z} matrix index

  • tileRow – identifier of {y} matrix index

  • tileCol – identifier of {x} matrix index

Returns

HTTP response

pygeoapi.flask_app.get_collection_tiles_metadata(collection_id=None, tileMatrixSetId=None)[source]

OGC open api collection tiles service metadata

Parameters
  • collection_id – collection identifier

  • tileMatrixSetId – identifier of tile matrix set

Returns

HTTP response

pygeoapi.flask_app.get_process_job_result(process_id=None, job_id=None)[source]

OGC API - Processes job result endpoint

Parameters
  • process_id – process identifier

  • job_id – job identifier

Returns

HTTP response

pygeoapi.flask_app.get_process_job_result_resource(process_id, job_id, resource)[source]

OGC API - Processes job result resource endpoint

Parameters
  • process_id – process identifier

  • job_id – job identifier

  • resource – job resource

Returns

HTTP response

pygeoapi.flask_app.get_process_jobs(process_id=None, job_id=None)[source]

OGC API - Processes jobs endpoint

Parameters
  • process_id – process identifier

  • job_id – job identifier

Returns

HTTP response

pygeoapi.flask_app.get_processes(process_id=None)[source]

OGC API - Processes description endpoint

Parameters

process_id – process identifier

Returns

HTTP response

pygeoapi.flask_app.get_response(result: tuple)[source]

Creates a Flask Response object and updates matching headers.

Parameters

result – The result of the API call. This should be a tuple of (headers, status, content).

Returns

A Response instance.

pygeoapi.flask_app.landing_page()[source]

OGC API landing page endpoint

Returns

HTTP response

pygeoapi.flask_app.openapi()[source]

OpenAPI endpoint

Returns

HTTP response

pygeoapi.flask_app.stac_catalog_path(path)[source]

STAC path endpoint

Parameters

path – path

Returns

HTTP response

pygeoapi.flask_app.stac_catalog_root()[source]

STAC root endpoint

Returns

HTTP response

Logging

Logging system

pygeoapi.log.setup_logger(logging_config)[source]

Setup configuration

Parameters

logging_config – logging specific configuration

Returns

void (creates logging instance)

OpenAPI

pygeoapi.openapi.gen_media_type_object(media_type, api_type, path)[source]

Generates an OpenAPI Media Type Object

Parameters
  • media_type – MIME type

  • api_type – OGC API type

  • path – local path of OGC API parameter or schema definition

Returns

dict of media type object

pygeoapi.openapi.gen_response_object(description, media_type, api_type, path)[source]

Generates an OpenAPI Response Object

Parameters
  • description – text description of response

  • media_type – MIME type

  • api_type – OGC API type

Returns

dict of response object

pygeoapi.openapi.get_oas(cfg, version='3.0')[source]

Stub to generate OpenAPI Document

Parameters
  • cfg – configuration object

  • version – version of OpenAPI (default 3.0)

Returns

OpenAPI definition YAML dict

pygeoapi.openapi.get_oas_30(cfg)[source]

Generates an OpenAPI 3.0 Document

Parameters

cfg – configuration object

Returns

OpenAPI definition YAML dict

pygeoapi.openapi.validate_openapi_document(instance_dict)[source]

Validate an OpenAPI document against the OpenAPI schema

Parameters

instance_dict – dict of OpenAPI instance

Returns

bool of validation

Plugins

Plugin loader

exception pygeoapi.plugin.InvalidPluginError[source]

Bases: Exception

Invalid plugin

__weakref__

list of weak references to the object (if defined)

pygeoapi.plugin.PLUGINS = {'formatter': {'CSV': 'pygeoapi.formatter.csv_.CSVFormatter'}, 'process': {'HelloWorld': 'pygeoapi.process.hello_world.HelloWorldProcessor'}, 'process_manager': {'Dummy': 'pygeoapi.process.manager.dummy.DummyManager', 'TinyDB': 'pygeoapi.process.manager.tinydb_.TinyDBManager'}, 'provider': {'CSV': 'pygeoapi.provider.csv_.CSVProvider', 'Elasticsearch': 'pygeoapi.provider.elasticsearch_.ElasticsearchProvider', 'ElasticsearchCatalogue': 'pygeoapi.provider.elasticsearch_.ElasticsearchCatalogueProvider', 'FileSystem': 'pygeoapi.provider.filesystem.FileSystemProvider', 'GeoJSON': 'pygeoapi.provider.geojson.GeoJSONProvider', 'MVT': 'pygeoapi.provider.mvt.MVTProvider', 'MongoDB': 'pygeoapi.provider.mongo.MongoProvider', 'OGR': 'pygeoapi.provider.ogr.OGRProvider', 'PostgreSQL': 'pygeoapi.provider.postgresql.PostgreSQLProvider', 'SQLiteGPKG': 'pygeoapi.provider.sqlite.SQLiteGPKGProvider', 'SensorThings': 'pygeoapi.provider.sensorthings.SensorThingsProvider', 'TinyDBCatalogue': 'pygeoapi.provider.tinydb_.TinyDBCatalogueProvider', 'rasterio': 'pygeoapi.provider.rasterio_.RasterioProvider', 'xarray': 'pygeoapi.provider.xarray_.XarrayProvider', 'xarray-edr': 'pygeoapi.provider.xarray_edr.XarrayEDRProvider'}}

Loads provider plugins to be used by pygeoapi,formatters and processes available

pygeoapi.plugin.load_plugin(plugin_type, plugin_def)[source]

loads plugin by name

Parameters
  • plugin_type – type of plugin (provider, formatter)

  • plugin_def – plugin definition

Returns

plugin object

Utils

Generic util functions used in the code

class pygeoapi.util.JobStatus[source]

Bases: enum.Enum

Enum for the job status options specified in the WPS 2.0 specification

pygeoapi.util.dategetter(date_property, collection)[source]

Attempts to obtain a date value from a collection.

Parameters
  • date_property – property representing the date

  • collection – dictionary to check within

Returns

str (ISO8601) representing the date (allowing for an open interval using null)

pygeoapi.util.file_modified_iso8601(filepath)[source]

Provide a file’s ctime in ISO8601

Parameters

filepath – path to file

Returns

string of ISO8601

pygeoapi.util.filter_dict_by_key_value(dict_, key, value)[source]

helper function to filter a dict by a dict key

Parameters
  • dictdict

  • key – dict key

  • value – dict key value

Returns

filtered dict

pygeoapi.util.filter_providers_by_type(providers, type)[source]

helper function to filter a list of providers by type

Parameters
  • providerslist

  • type – str

Returns

filtered dict provider

pygeoapi.util.format_datetime(value, format_='%Y-%m-%dT%H:%M:%S.%fZ')[source]

Parse datetime as ISO 8601 string; re-present it in particular format for display in HTML

Parameters
  • valuestr of ISO datetime

  • formatstr of datetime format for strftime

Returns

string

pygeoapi.util.format_duration(start, end=None)[source]

Parse a start and (optional) end datetime as ISO 8601 strings, calculate the difference, and return that duration as a string.

Parameters
  • startstr of ISO datetime

  • endstr of ISO datetime, defaults to start for a 0 duration

Returns

string

pygeoapi.util.get_breadcrumbs(urlpath)[source]

helper function to make breadcrumbs from a URL path

Parameters

urlpath – URL path

Returns

list of dict objects of labels and links

pygeoapi.util.get_envelope(coords_list: List[List[float]])[source]

helper function to get the envelope for a given coordinates list through the Shapely API.

Parameters

coords_list – list of coordinates

Returns

list of the envelope’s coordinates

pygeoapi.util.get_mimetype(filename)[source]

helper function to return MIME type of a given file

Parameters

filename – filename (with extension)

Returns

MIME type of given filename

pygeoapi.util.get_path_basename(urlpath)[source]

Helper function to derive file basename

Parameters

urlpath – URL path

Returns

string of basename of URL path

pygeoapi.util.get_provider_by_type(providers, provider_type)[source]

helper function to load a provider by a provider type

Parameters
  • providerslist of providers

  • provider_type – type of provider (feature)

Returns

provider based on type

pygeoapi.util.get_provider_default(providers)[source]

helper function to get a resource’s default provider

Parameters

providerslist of providers

Returns

filtered dict

pygeoapi.util.get_typed_value(value)[source]

Derive true type from data value

Parameters

value – value

Returns

value as a native Python data type

pygeoapi.util.human_size(nbytes)[source]

Provides human readable file size

source: https://stackoverflow.com/a/14996816

Parameters
  • nbytes – int of file size (bytes)

  • units – list of unit abbreviations

Returns

string of human readable filesize

pygeoapi.util.is_url(urlstring)[source]

Validation function that determines whether a candidate URL should be considered a URI. No remote resource is obtained; this does not check the existence of any remote resource. :param urlstring: str to be evaluated as candidate URL. :returns: bool of whether the URL looks like a URL.

pygeoapi.util.json_serial(obj)[source]

helper function to convert to JSON non-default types (source: https://stackoverflow.com/a/22238613) :param obj: object to be evaluated :returns: JSON non-default type to str

pygeoapi.util.read_data(path)[source]

helper function to read data (file or networrk)

pygeoapi.util.render_j2_template(config, template, data, locale_=None)[source]

render Jinja2 template

Parameters
  • config – dict of configuration

  • template – template (relative path)

  • data – dict of data

  • locale – the requested output Locale

Returns

string of rendered template

pygeoapi.util.str2bool(value)[source]

helper function to return Python boolean type (source: https://stackoverflow.com/a/715468)

Parameters

value – value to be evaluated

Returns

bool of whether the value is boolean-ish

pygeoapi.util.to_json(dict_, pretty=False)[source]

Serialize dict to json

Parameters
  • dictdict of JSON representation

  • prettybool of whether to prettify JSON (default is False)

Returns

JSON string representation

pygeoapi.util.url_join(*parts)[source]

helper function to join a URL from a number of parts/fragments. Implemented because urllib.parse.urljoin strips subpaths from host urls if they are specified

Per https://github.com/geopython/pygeoapi/issues/695

Parameters

parts – list of parts to join

Returns

str of resulting URL

pygeoapi.util.yaml_load(fh)[source]

serializes a YAML files into a pyyaml object

Parameters

fh – file handle

Returns

dict representation of YAML

Formatter package

Output formatter package

Base class

class pygeoapi.formatter.base.BaseFormatter(formatter_def)[source]

Bases: object

generic Formatter ABC

__init__(formatter_def)[source]

Initialize object

Parameters

formatter_def – formatter definition

Returns

pygeoapi.formatter.base.BaseFormatter

__repr__()[source]

Return repr(self).

__weakref__

list of weak references to the object (if defined)

write(options={}, data=None)[source]

Generate data in specified format

Parameters
  • options – CSV formatting options

  • data – dict representation of GeoJSON object

Returns

string representation of format

exception pygeoapi.formatter.base.FormatterGenericError[source]

Bases: Exception

formatter generic error

__weakref__

list of weak references to the object (if defined)

exception pygeoapi.formatter.base.FormatterSerializationError[source]

Bases: pygeoapi.formatter.base.FormatterGenericError

formatter serialization error

csv

class pygeoapi.formatter.csv_.CSVFormatter(formatter_def)[source]

Bases: pygeoapi.formatter.base.BaseFormatter

CSV formatter

__init__(formatter_def)[source]

Initialize object

Parameters

formatter_def – formatter definition

Returns

pygeoapi.formatter.csv_.CSVFormatter

__repr__()[source]

Return repr(self).

write(options={}, data=None)[source]

Generate data in CSV format

Parameters
  • options – CSV formatting options

  • data – dict of GeoJSON data

Returns

string representation of format

Process package

OGC process package, each process is an independent module

Base class

class pygeoapi.process.base.BaseProcessor(processor_def, process_metadata)[source]

Bases: object

generic Processor ABC. Processes are inherited from this class

__init__(processor_def, process_metadata)[source]

Initialize object

Parameters
  • processor_def – processor definition

  • process_metadata – process metadata dict

Returns

pygeoapi.processor.base.BaseProvider

__repr__()[source]

Return repr(self).

__weakref__

list of weak references to the object (if defined)

execute()[source]

execute the process

Returns

tuple of MIME type and process response

exception pygeoapi.process.base.ProcessorExecuteError[source]

Bases: pygeoapi.process.base.ProcessorGenericError

query / backend error

exception pygeoapi.process.base.ProcessorGenericError[source]

Bases: Exception

processor generic error

__weakref__

list of weak references to the object (if defined)

hello_world

Hello world example process

class pygeoapi.process.hello_world.HelloWorldProcessor(processor_def)[source]

Bases: pygeoapi.process.base.BaseProcessor

Hello World Processor example

__init__(processor_def)[source]

Initialize object

Parameters

processor_def – provider definition

Returns

pygeoapi.process.hello_world.HelloWorldProcessor

__repr__()[source]

Return repr(self).

execute(data)[source]

execute the process

Returns

tuple of MIME type and process response

pygeoapi.process.hello_world.PROCESS_METADATA = {'description': {'en': 'An example process that takes a name as input, and echoes it back as output. Intended to demonstrate a simple process with a single literal input.', 'fr': 'Un exemple de processus qui prend un nom en entrée et le renvoie en sortie. Destiné à démontrer un processus simple avec une seule entrée littérale.'}, 'example': {'inputs': {'message': 'An optional message.', 'name': 'World'}}, 'id': 'hello-world', 'inputs': {'message': {'description': 'An optional message to echo as well', 'keywords': ['message'], 'maxOccurs': 1, 'metadata': None, 'minOccurs': 0, 'schema': {'type': 'string'}, 'title': 'Message'}, 'name': {'description': 'The name of the person or entity that you wish tobe echoed back as an output', 'keywords': ['full name', 'personal'], 'maxOccurs': 1, 'metadata': None, 'minOccurs': 1, 'schema': {'type': 'string'}, 'title': 'Name'}}, 'keywords': ['hello world', 'example', 'echo'], 'links': [{'type': 'text/html', 'rel': 'canonical', 'title': 'information', 'href': 'https://example.org/process', 'hreflang': 'en-US'}], 'outputs': {'echo': {'description': 'A "hello world" echo with the name and (optional) message submitted for processing', 'schema': {'contentMediaType': 'application/json', 'type': 'object'}, 'title': 'Hello, world'}}, 'title': {'en': 'Hello World', 'fr': 'Bonjour le Monde'}, 'version': '0.2.0'}

Process metadata and description

Provider

Provider module containing the plugins wrapping data sources

Base class

class pygeoapi.provider.base.BaseProvider(provider_def)[source]

Bases: object

generic Provider ABC

__init__(provider_def)[source]

Initialize object

Parameters

provider_def – provider definition

Returns

pygeoapi.provider.base.BaseProvider

__repr__()[source]

Return repr(self).

__weakref__

list of weak references to the object (if defined)

create(new_feature)[source]

Create a new feature

delete(identifier)[source]

Deletes an existing feature

Parameters

identifier – feature id

get(identifier)[source]

query the provider by id

Parameters

identifier – feature id

Returns

dict of single GeoJSON feature

get_coverage_domainset()[source]

Provide coverage domainset

Returns

CIS JSON object of domainset metadata

get_coverage_rangetype()[source]

Provide coverage rangetype

Returns

CIS JSON object of rangetype metadata

get_data_path(baseurl, urlpath, dirpath)[source]

Gets directory listing or file description or raw file dump

Parameters
  • baseurl – base URL of endpoint

  • urlpath – base path of URL

  • dirpath – directory basepath (equivalent of URL)

Returns

dict of file listing or dict of GeoJSON item or raw file

get_fields()[source]

Get provider field information (names, types)

Returns

dict of fields

get_metadata()[source]

Provide data/file metadata

Returns

dict of metadata construct (format determined by provider/standard)

query()[source]

query the provider

Returns

dict of 0..n GeoJSON features or coverage data

update(identifier, new_feature)[source]

Updates an existing feature id with new_feature

Parameters
  • identifier – feature id

  • new_feature – new GeoJSON feature dictionary

exception pygeoapi.provider.base.ProviderConnectionError[source]

Bases: pygeoapi.provider.base.ProviderGenericError

provider connection error

exception pygeoapi.provider.base.ProviderGenericError[source]

Bases: Exception

provider generic error

__weakref__

list of weak references to the object (if defined)

exception pygeoapi.provider.base.ProviderInvalidQueryError[source]

Bases: pygeoapi.provider.base.ProviderGenericError

provider invalid query error

exception pygeoapi.provider.base.ProviderItemNotFoundError[source]

Bases: pygeoapi.provider.base.ProviderGenericError

provider item not found query error

exception pygeoapi.provider.base.ProviderNoDataError[source]

Bases: pygeoapi.provider.base.ProviderGenericError

provider no data error

exception pygeoapi.provider.base.ProviderNotFoundError[source]

Bases: pygeoapi.provider.base.ProviderGenericError

provider not found error

exception pygeoapi.provider.base.ProviderQueryError[source]

Bases: pygeoapi.provider.base.ProviderGenericError

provider query error

exception pygeoapi.provider.base.ProviderTypeError[source]

Bases: pygeoapi.provider.base.ProviderGenericError

provider type error

exception pygeoapi.provider.base.ProviderVersionError[source]

Bases: pygeoapi.provider.base.ProviderGenericError

provider incorrect version error

CSV provider

class pygeoapi.provider.csv_.CSVProvider(provider_def)[source]

Bases: pygeoapi.provider.base.BaseProvider

CSV provider

_load(startindex=0, limit=10, resulttype='results', identifier=None, bbox=[], datetime_=None, properties=[], select_properties=[], skip_geometry=False, q=None)[source]

Load CSV data

Parameters
  • startindex – starting record to return (default 0)

  • limit – number of records to return (default 10)

  • datetime – temporal (datestamp or extent)

  • resulttype – return results or hit limit (default results)

  • properties – list of tuples (name, value)

  • select_properties – list of property names

  • skip_geometry – bool of whether to skip geometry (default False)

  • q – full-text search term(s)

Returns

dict of GeoJSON FeatureCollection

get(identifier, **kwargs)[source]

query CSV id

Parameters

identifier – feature id

Returns

dict of single GeoJSON feature

get_fields()[source]

Get provider field information (names, types)

Returns

dict of fields

query(startindex=0, limit=10, resulttype='results', bbox=[], datetime_=None, properties=[], sortby=[], select_properties=[], skip_geometry=False, q=None, **kwargs)[source]

CSV query

Parameters
  • startindex – starting record to return (default 0)

  • limit – number of records to return (default 10)

  • resulttype – return results or hit limit (default results)

  • bbox – bounding box [minx,miny,maxx,maxy]

  • datetime – temporal (datestamp or extent)

  • properties – list of tuples (name, value)

  • sortby – list of dicts (property, order)

  • select_properties – list of property names

  • skip_geometry – bool of whether to skip geometry (default False)

  • q – full-text search term(s)

Returns

dict of GeoJSON FeatureCollection

Elasticsearch provider

GeoJSON

class pygeoapi.provider.geojson.GeoJSONProvider(provider_def)[source]

Bases: pygeoapi.provider.base.BaseProvider

Provider class backed by local GeoJSON files

This is meant to be simple (no external services, no dependencies, no schema)

at the expense of performance (no indexing, full serialization roundtrip on each request)

Not thread safe, a single server process is assumed

This implementation uses the feature ‘id’ heavily and will override any ‘id’ provided in the original data. The feature ‘properties’ will be preserved.

TODO: * query method should take bbox * instead of methods returning FeatureCollections, we should be yielding Features and aggregating in the view * there are strict id semantics; all features in the input GeoJSON file must be present and be unique strings. Otherwise it will break. * How to raise errors in the provider implementation such that * appropriate HTTP responses will be raised

_load(skip_geometry=None, properties=[], select_properties=[])[source]

Load and validate the source GeoJSON file at self.data

Yes loading from disk, deserializing and validation happens on every request. This is not efficient.

create(new_feature)[source]

Create a new feature

Parameters

new_feature – new GeoJSON feature dictionary

delete(identifier)[source]

Deletes an existing feature

Parameters

identifier – feature id

get(identifier, **kwargs)[source]

query the provider by id

Parameters

identifier – feature id

Returns

dict of single GeoJSON feature

get_fields()[source]

Get provider field information (names, types)

Returns

dict of fields

query(startindex=0, limit=10, resulttype='results', bbox=[], datetime_=None, properties=[], sortby=[], select_properties=[], skip_geometry=False, q=None, **kwargs)[source]

query the provider

Parameters
  • startindex – starting record to return (default 0)

  • limit – number of records to return (default 10)

  • resulttype – return results or hit limit (default results)

  • bbox – bounding box [minx,miny,maxx,maxy]

  • datetime – temporal (datestamp or extent)

  • properties – list of tuples (name, value)

  • sortby – list of dicts (property, order)

  • select_properties – list of property names

  • skip_geometry – bool of whether to skip geometry (default False)

  • q – full-text search term(s)

Returns

FeatureCollection dict of 0..n GeoJSON features

update(identifier, new_feature)[source]

Updates an existing feature id with new_feature

Parameters
  • identifier – feature id

  • new_feature – new GeoJSON feature dictionary

OGR

class pygeoapi.provider.ogr.CommonSourceHelper(provider)[source]

Bases: pygeoapi.provider.ogr.SourceHelper

SourceHelper for most common OGR Source types: Shapefile, GeoPackage, SQLite, GeoJSON etc.

close()[source]

OGR Driver-specific handling of closing dataset. If ExecuteSQL has been (successfully) called must close ResultSet explicitly. https://gis.stackexchange.com/questions/114112/explicitly-close-a-ogr-result-object-from-a-call-to-executesql # noqa

disable_paging()[source]

Disable paged access to dataset (OGR Driver-specific)

enable_paging(startindex=- 1, limit=- 1)[source]

Enable paged access to dataset (OGR Driver-specific) using OGR SQL https://gdal.org/user/ogr_sql_dialect.html e.g. SELECT * FROM poly LIMIT 10 OFFSET 30

get_layer()[source]

Gets OGR Layer from opened OGR dataset. When startindex defined 1 or greater will invoke OGR SQL SELECT with LIMIT and OFFSET and return as Layer as ResultSet from ExecuteSQL on dataset. :return: OGR layer object

class pygeoapi.provider.ogr.ESRIJSONHelper(provider)[source]

Bases: pygeoapi.provider.ogr.CommonSourceHelper

disable_paging()[source]

Disable paged access to dataset (OGR Driver-specific)

enable_paging(startindex=- 1, limit=- 1)[source]

Enable paged access to dataset (OGR Driver-specific)

get_layer()[source]

Gets OGR Layer from opened OGR dataset. When startindex defined 1 or greater will invoke OGR SQL SELECT with LIMIT and OFFSET and return as Layer as ResultSet from ExecuteSQL on dataset. :return: OGR layer object

exception pygeoapi.provider.ogr.InvalidHelperError[source]

Bases: Exception

Invalid helper

class pygeoapi.provider.ogr.OGRProvider(provider_def)[source]

Bases: pygeoapi.provider.base.BaseProvider

OGR Provider. Uses GDAL/OGR Python-bindings to access OGR Vector sources. References: https://pcjericks.github.io/py-gdalogr-cookbook/ https://gdal.org/ogr_formats.html (per-driver specifics).

In theory any OGR source type (Driver) could be used, although some Source Types are Driver-specific handling. This is handled in Source Helper classes, instantiated per Source-Type.

The following Source Types have been tested to work: GeoPackage (GPKG), SQLite, GeoJSON, ESRI Shapefile, WFS v2.

_load_source_helper(source_type)[source]

Loads Source Helper by name.

Parameters

type (Source) – Source type name

Returns

Source Helper object

_response_feature_collection(layer, limit)[source]

Assembles output from Layer query as GeoJSON FeatureCollection structure.

Returns

GeoJSON FeatureCollection

_response_feature_hits(layer)[source]

Assembles GeoJSON hits from OGR Feature count e.g: http://localhost:5000/collections/ hotosm_bdi_waterways/items?resulttype=hits

Returns

GeoJSON FeaturesCollection

get(identifier, **kwargs)[source]

Get Feature by id

Parameters

identifier – feature id

Returns

feature collection

get_fields()[source]

Get provider field information (names, types)

Returns

dict of fields

query(startindex=0, limit=10, resulttype='results', bbox=[], datetime_=None, properties=[], sortby=[], select_properties=[], skip_geometry=False, q=None, **kwargs)[source]

Query OGR source

Parameters
  • startindex – starting record to return (default 0)

  • limit – number of records to return (default 10)

  • resulttype – return results or hit limit (default results)

  • bbox – bounding box [minx,miny,maxx,maxy]

  • datetime – temporal (datestamp or extent)

  • properties – list of tuples (name, value)

  • sortby – list of dicts (property, order)

  • select_properties – list of property names

  • skip_geometry – bool of whether to skip geometry (default False)

  • q – full-text search term(s)

Returns

dict of 0..n GeoJSON features

class pygeoapi.provider.ogr.SourceHelper(provider)[source]

Bases: object

Helper classes for OGR-specific Source Types (Drivers). For some actions Driver-specific settings or processing is required. This is delegated to the OGR SourceHelper classes.

close()[source]

OGR Driver-specific handling of closing dataset. Default is no specific handling.

disable_paging()[source]

Disable paged access to dataset (OGR Driver-specific)

enable_paging(startindex=- 1, limit=- 1)[source]

Enable paged access to dataset (OGR Driver-specific)

get_layer()[source]

Default action to get a Layer object from opened OGR Driver. :return:

class pygeoapi.provider.ogr.WFSHelper(provider)[source]

Bases: pygeoapi.provider.ogr.SourceHelper

disable_paging()[source]

Disable paged access to dataset (OGR Driver-specific)

enable_paging(startindex=- 1, limit=- 1)[source]

Enable paged access to dataset (OGR Driver-specific)

pygeoapi.provider.ogr._ignore_gdal_error(inst, fn, *args, **kwargs) → Any[source]

Evaluate the function with the object instance.

Parameters
  • inst – Object instance

  • fn – String function name

  • args – List of positional arguments

  • kwargs – Keyword arguments

Returns

Any function evaluation result

pygeoapi.provider.ogr._silent_gdal_error(f)[source]

Decorator function for gdal

postgresql

class pygeoapi.provider.postgresql.DatabaseConnection(conn_dic, table, context='query')[source]

Bases: object

Database connection class to be used as ‘with’ statement. The class returns a connection object.

class pygeoapi.provider.postgresql.PostgreSQLProvider(provider_def)[source]

Bases: pygeoapi.provider.base.BaseProvider

Generic provider for Postgresql based on psycopg2 using sync approach and server side cursor (using support class DatabaseCursor)

_PostgreSQLProvider__get_where_clauses(properties=[], bbox=[])

Generarates WHERE conditions to be implemented in query. Private method mainly associated with query method :param properties: list of tuples (name, value) :param bbox: bounding box [minx,miny,maxx,maxy]

Returns

psycopg2.sql.Composed or psycopg2.sql.SQL

_PostgreSQLProvider__response_feature(row_data)

Assembles GeoJSON output from DB query

Parameters

row_data – DB row result

Returns

dict of GeoJSON Feature

_PostgreSQLProvider__response_feature_hits(hits)

Assembles GeoJSON/Feature number e.g: http://localhost:5000/collections/ hotosm_bdi_waterways/items?resulttype=hits

Returns

GeoJSON FeaturesCollection

_make_orderby(sortby)[source]

Private function: Make STA filter from query properties

Parameters

sortby – list of dicts (property, order)

Returns

STA $orderby string

get(identifier, **kwargs)[source]

Query the provider for a specific feature id e.g: /collections/hotosm_bdi_waterways/items/13990765

Parameters

identifier – feature id

Returns

GeoJSON FeaturesCollection

get_fields()[source]

Get fields from PostgreSQL table (columns are field)

Returns

dict of fields

get_next(cursor, identifier)[source]

Query next ID given current ID

Parameters

identifier – feature id

Returns

feature id

get_previous(cursor, identifier)[source]

Query previous ID given current ID

Parameters

identifier – feature id

Returns

feature id

query(startindex=0, limit=10, resulttype='results', bbox=[], datetime_=None, properties=[], sortby=[], select_properties=[], skip_geometry=False, q=None, **kwargs)[source]

Query Postgis for all the content. e,g: http://localhost:5000/collections/hotosm_bdi_waterways/items? limit=1&resulttype=results

Parameters
  • startindex – starting record to return (default 0)

  • limit – number of records to return (default 10)

  • resulttype – return results or hit limit (default results)

  • bbox – bounding box [minx,miny,maxx,maxy]

  • datetime – temporal (datestamp or extent)

  • properties – list of tuples (name, value)

  • sortby – list of dicts (property, order)

  • select_properties – list of property names

  • skip_geometry – bool of whether to skip geometry (default False)

  • q – full-text search term(s)

Returns

GeoJSON FeaturesCollection

sqlite/geopackage

class pygeoapi.provider.sqlite.SQLiteGPKGProvider(provider_def)[source]

Bases: pygeoapi.provider.base.BaseProvider

Generic provider for SQLITE and GPKG using sqlite3 module. This module requires install of libsqlite3-mod-spatialite TODO: DELETE, UPDATE, CREATE

_SQLiteGPKGProvider__get_where_clauses(properties=[], bbox=[])

Generarates WHERE conditions to be implemented in query. Private method mainly associated with query method.

Method returns part of the SQL query, plus tupple to be used in the sqlite query method

Parameters
  • properties – list of tuples (name, value)

  • bbox – bounding box [minx,miny,maxx,maxy]

Returns

str, tuple

_SQLiteGPKGProvider__load()

Private method for loading spatiallite, get the table structure and dump geometry

Returns

sqlite3.Cursor

_SQLiteGPKGProvider__response_feature(row_data)

Assembles GeoJSON output from DB query

Parameters

row_data – DB row result

Returns

dict of GeoJSON Feature

_SQLiteGPKGProvider__response_feature_hits(hits)

Assembles GeoJSON/Feature number

Returns

GeoJSON FeaturesCollection

get(identifier, **kwargs)[source]

Query the provider for a specific feature id e.g: /collections/countries/items/1

Parameters

identifier – feature id

Returns

GeoJSON FeaturesCollection

get_fields()[source]

Get fields from sqlite table (columns are field)

Returns

dict of fields

query(startindex=0, limit=10, resulttype='results', bbox=[], datetime_=None, properties=[], sortby=[], select_properties=[], skip_geometry=False, q=None, **kwargs)[source]

Query SQLite/GPKG for all the content. e,g: http://localhost:5000/collections/countries/items? limit=5&startindex=2&resulttype=results&continent=Europe&admin=Albania&bbox=29.3373,-3.4099,29.3761,-3.3924 http://localhost:5000/collections/countries/items?continent=Africa&bbox=29.3373,-3.4099,29.3761,-3.3924

Parameters
  • startindex – starting record to return (default 0)

  • limit – number of records to return (default 10)

  • resulttype – return results or hit limit (default results)

  • bbox – bounding box [minx,miny,maxx,maxy]

  • datetime – temporal (datestamp or extent)

  • properties – list of tuples (name, value)

  • sortby – list of dicts (property, order)

  • select_properties – list of property names

  • skip_geometry – bool of whether to skip geometry (default False)

  • q – full-text search term(s)

Returns

GeoJSON FeaturesCollection