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)

static _create_crs_transform_spec(config: dict, query_crs_uri: Optional[str] = None) → Union[None, pygeoapi.util.CrsTransformSpec][source]

Create a CrsTransformSpec instance based on provider config and crs query parameter.

Parameters:
  • config (dict) – Provider config dictionary.
  • query_crs_uri (str, optional) – Uniform resource identifier of the coordinate reference system (CRS) specified in query parameter (if specified).
Raises:
  • ValueError – Error raised if the CRS specified in the query parameter is not in the list of supported CRSs of the provider.
  • CRSError – Error raised if no CRS could be identified from the query crs parameter (URI).
Returns:

CrsTransformSpec instance if the CRS specified in query parameter differs from the storage CRS, else None.

Return type:

Union[None, CrsTransformSpec]

static _set_content_crs_header(headers: dict, config: dict, query_crs_uri: Optional[str] = None)[source]

Set the Content-Crs header in responses from providers of Feature type.

Parameters:
  • headers (dict) – Response headers dictionary.
  • config (dict) – Provider config dictionary.
  • query_crs_uri (str, optional) – Uniform resource identifier of the coordinate reference system specified in query parameter (if specified).
delete_job(job_id) → Tuple[dict, int, str][source]

Delete a process job

Parameters: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/Django Request into an APIRequest`using the :func:`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, HTTPStatus.OK, 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, HTTPStatus.OK, 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
data

Returns the additional data send with the Request (bytes)

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, force_encoding: str = None, **custom_headers) → 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.
  • force_encoding – An optional Content-Encoding header override.
Returns:

A header dict

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
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
params

Returns the Request query parameters dict

path_info

Returns the web server request path info part

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', 'mvt': 'application/vnd.mapbox-vector-tile', 'png': 'image/png'}

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

pygeoapi.api.HEADERS = {'Content-Type': 'application/json', 'X-Powered-By': 'pygeoapi 0.16.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.gzip(func)[source]

Decorator that compresses the content of an outgoing API result instance if the Content-Encoding response header was set to gzip.

Parameters:func – decorated function
Returns:func
pygeoapi.api.pre_process(func)[source]

Decorator that transforms an incoming Request instance specific to the web framework (i.e. Flask, Starlette or Django) 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

pygeoapi.api.validate_subset(value: str) → dict[source]

Helper function to validate subset parameter

Parameters:valuesubset parameter
Returns:dict of axis/values

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_map(collection_id, style_id=None)[source]

OGC API - Maps map render endpoint

Parameters:
  • collection_id – collection identifier
  • style_id – style 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_job_result(job_id=None)[source]

OGC API - Processes job result endpoint

Parameters:job_id – job identifier
Returns:HTTP response
pygeoapi.flask_app.get_job_result_resource(job_id, resource)[source]

OGC API - Processes job result resource endpoint

Parameters:
  • job_id – job identifier
  • resource – job resource
Returns:

HTTP response

pygeoapi.flask_app.get_jobs(job_id=None)[source]

OGC API - Processes jobs endpoint

Parameters: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.generate_openapi_document(cfg_file: Union[pathlib.Path, _io.TextIOWrapper], output_format: pygeoapi.models.openapi.OAPIFormat)[source]

Generate an OpenAPI document from the configuration file

Parameters:
  • cfg_file – configuration Path instance
  • output_format – output format for OpenAPI document
Returns:

content of the OpenAPI document in the output format requested

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', 'MongoDB': 'pygeoapi.process.manager.mongodb_.MongoDBManager', 'TinyDB': 'pygeoapi.process.manager.tinydb_.TinyDBManager'}, 'provider': {'AzureBlobStorage': 'pygeoapi.provider.azure_.AzureBlobStorageProvider', 'CSV': 'pygeoapi.provider.csv_.CSVProvider', 'ERDDAPTabledap': 'pygeoapi.provider.erddap.TabledapProvider', 'ESRI': 'pygeoapi.provider.esri.ESRIServiceProvider', 'Elasticsearch': 'pygeoapi.provider.elasticsearch_.ElasticsearchProvider', 'ElasticsearchCatalogue': 'pygeoapi.provider.elasticsearch_.ElasticsearchCatalogueProvider', 'FileSystem': 'pygeoapi.provider.filesystem.FileSystemProvider', 'GeoJSON': 'pygeoapi.provider.geojson.GeoJSONProvider', 'Hateoas': 'pygeoapi.provider.hateoas.HateoasProvider', 'MVT': 'pygeoapi.provider.mvt.MVTProvider', 'MapScript': 'pygeoapi.provider.mapscript_.MapScriptProvider', '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', 'Socrata': 'pygeoapi.provider.socrata.SODAServiceProvider', 'TinyDBCatalogue': 'pygeoapi.provider.tinydb_.TinyDBCatalogueProvider', 'WMSFacade': 'pygeoapi.provider.wms_facade.WMSFacadeProvider', '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: str, plugin_def: dict) → Any[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.CrsTransformSpec(source_crs_uri: str, source_crs_wkt: str, target_crs_uri: str, target_crs_wkt: str)[source]

Bases: object

__weakref__

list of weak references to the object (if defined)

class pygeoapi.util.JobStatus[source]

Bases: enum.Enum

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

class pygeoapi.util.ProcessExecutionMode[source]

Bases: enum.Enum

An enumeration.

class pygeoapi.util.RequestedProcessExecutionMode[source]

Bases: enum.Enum

An enumeration.

class pygeoapi.util.UrlPrefetcher[source]

Bases: object

Prefetcher to get HTTP headers for specific URLs. Allows a maximum of 1 redirect by default.

__init__()[source]

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

__weakref__

list of weak references to the object (if defined)

get_headers(url: str, **kwargs) → requests.structures.CaseInsensitiveDict[source]

Issues an HTTP HEAD request to the given URL. Returns a case-insensitive dictionary of all headers. If the request times out (defaults to 1 second unless timeout keyword argument is set), or the response has a bad status code, an empty dictionary is returned.

pygeoapi.util.crs_transform(func)[source]

Decorator that transforms the geometry’s/geometries’ coordinates of a Feature/FeatureCollection.

This function can be used to decorate another function which returns either a Feature or a FeatureCollection (GeoJSON-like dict). For a FeatureCollection, the Features are stored in a ´list´ available at the ‘features’ key of the returned dict. For each Feature, the geometry is available at the ‘geometry’ key. The decorated function may take a ‘crs_transform_spec’ parameter, which accepts a CrsTransformSpec instance as value. If the CrsTransformSpec instance represents a coordinates transformation between two different CRSs, the coordinates of the Feature’s/FeatureCollection’s geometry/geometries will be transformed before returning the Feature/FeatureCollection. If the ‘crs_transform_spec’ parameter is not given, passed None or passed a CrsTransformSpec instance which does not represent a coordinates transformation, the Feature/FeatureCollection is returned unchanged. This decorator can for example be use to help supporting coordinates transformation of Feature/FeatureCollection dict objects returned by the get and query methods of (new or with no native support for transformations) providers of type ‘feature’.

Parameters:func (callable) – Function to decorate.
Returns:Decorated function.
Return type:callable
pygeoapi.util.crs_transform_feature(feature, transform_func)[source]

Transform the coordinates of a Feature.

Parameters:
  • feature (dict) – Feature (GeoJSON-like dict) to transform.
  • transform_func (callable) – Function that transforms the coordinates of a GeomObject instance.
Returns:

None

pygeoapi.util.dategetter(date_property: str, collection: dict) → str[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: pathlib.Path) → str[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_: dict, key: str, value: str) → dict[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: list, type: str) → dict[source]

helper function to filter a list of providers by type

Parameters:
  • providerslist
  • type – str
Returns:

filtered dict provider

pygeoapi.util.format_datetime(value: str, format_: str = '%Y-%m-%dT%H:%M:%S.%fZ') → str[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: str, end: str = None) → str[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_api_rules(config: dict) → pygeoapi.models.config.APIRules[source]

Extracts the default API design rules from the given configuration.

Parameters:config – Current pygeoapi configuration (dictionary).
Returns:An APIRules instance.
pygeoapi.util.get_base_url(config: dict) → str[source]

Returns the full pygeoapi base URL.

pygeoapi.util.get_breadcrumbs(urlpath: str) → list[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_crs_from_uri(uri: str) → pyproj.crs.crs.CRS[source]

Get a pyproj.CRS instance from a CRS URI. Author: @MTachon

Parameters:uri (str) – Uniform resource identifier of the coordinate reference system.
Raises:CRSError – Error raised if no CRS could be identified from the URI.
Returns:pyproj.CRS instance matching the input URI.
Return type:pyproj.CRS
pygeoapi.util.get_envelope(coords_list: List[List[float]]) → list[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: str) → str[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: str) → str[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: list, provider_type: str) → dict[source]

helper function to load a provider by a provider type

Parameters:
  • providerslist of providers
  • provider_type – type of provider (e.g. feature)
Returns:

provider based on type

pygeoapi.util.get_provider_default(providers: list) → dict[source]

helper function to get a resource’s default provider

Parameters:providerslist of providers
Returns:filtered dict
pygeoapi.util.get_supported_crs_list(config: dict, default_crs_list: list) → list[source]

Helper function to get a complete list of supported CRSs from a (Provider) config dict. Result should always include a default CRS according to OAPIF Part 2 OGC Standard. This will be the default when no CRS list in config or added when (partially) missing in config.

Author: @justb4

Parameters:
  • config – dictionary with or without a list of CRSs
  • default_crs_list – default CRS alternatives, first is default
Returns:

list of supported CRSs

pygeoapi.util.get_transform_from_crs(crs_in: pyproj.crs.crs.CRS, crs_out: pyproj.crs.crs.CRS, always_xy: bool = False) → Callable[[Union[shapely.geometry.collection.GeometryCollection, shapely.geometry.polygon.LinearRing, shapely.geometry.linestring.LineString, shapely.geometry.multilinestring.MultiLineString, shapely.geometry.multipoint.MultiPoint, shapely.geometry.multipolygon.MultiPolygon, shapely.geometry.point.Point, shapely.geometry.polygon.Polygon]], Union[shapely.geometry.collection.GeometryCollection, shapely.geometry.polygon.LinearRing, shapely.geometry.linestring.LineString, shapely.geometry.multilinestring.MultiLineString, shapely.geometry.multipoint.MultiPoint, shapely.geometry.multipolygon.MultiPolygon, shapely.geometry.point.Point, shapely.geometry.polygon.Polygon]][source]

Get transformation function from two pyproj.CRS instances.

Get function to transform the coordinates of a Shapely geometrical object from one coordinate reference system to another.

Parameters:
  • crs_in (pyproj.CRS) – Coordinate Reference System of the input geometrical object.
  • crs_out (pyproj.CRS) – Coordinate Reference System of the output geometrical object.
  • always_xy (bool) – should axis order be forced to x,y (lon, lat) even if CRS declares y,x (lat,lon)
Returns:

Function to transform the coordinates of a GeomObject.

Return type:

callable

pygeoapi.util.get_typed_value(value: str) → Union[float, int, str][source]

Derive true type from data value

Parameters:value – value
Returns:value as a native Python data type
pygeoapi.util.human_size(nbytes: int) → str[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: str) → bool[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.

Parameters:urlstringstr to be evaluated as candidate URL.
Returns:bool of whether the URL looks like a URL.
pygeoapi.util.json_serial(obj: Any) → str[source]

helper function to convert to JSON non-default types (source: https://stackoverflow.com/a/22238613)

Parameters:objobject to be evaluated
Returns:JSON non-default type to str
pygeoapi.util.read_data(path: Union[pathlib.Path, str]) → Union[bytes, str][source]

helper function to read data (file or network)

pygeoapi.util.render_j2_template(config: dict, template: pathlib.Path, data: dict, locale_: str = None) → str[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: Union[bool, str]) → bool[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_: dict, pretty: bool = False) → str[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.transform_bbox(bbox: list, from_crs: str, to_crs: str) → list[source]

helper function to transform a bounding box (bbox) from a source to a target CRS. CRSs in URI str format. Uses pyproj Transformer.

Parameters:
  • bbox – list of coordinates in ‘from_crs’ projection
  • from_crs – CRS URI to transform from
  • to_crs – CRS URI to transform to
Raises:

CRSError – Error raised if no CRS could be identified from an URI.

Returns:

list of 4 or 6 coordinates

pygeoapi.util.url_join(*parts) → str[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: IO) → dict[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: dict)[source]

Bases: object

generic Formatter ABC

__init__(formatter_def: dict)[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: dict = {}, data: dict = None) → str[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: dict)[source]

Bases: pygeoapi.formatter.base.BaseFormatter

CSV formatter

__init__(formatter_def: dict)[source]

Initialize object

Parameters:formatter_def – formatter definition
Returns:pygeoapi.formatter.csv_.CSVFormatter
__repr__()[source]

Return repr(self).

write(options: dict = {}, data: dict = None) → str[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: dict, process_metadata: dict)[source]

Bases: object

generic Processor ABC. Processes are inherited from this class

__init__(processor_def: dict, process_metadata: dict)[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(data: dict) → Tuple[str, Any][source]

execute the process

Parameters:data – Dict with the input data that the process needs in order to execute
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

Parameters:data – Dict with the input data that the process needs in order to execute
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'}}, 'jobControlOptions': ['sync-execute', 'async-execute'], 'keywords': ['hello world', 'example', 'echo'], 'links': [{'type': 'text/html', 'rel': 'about', '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)

_load_and_prepare_item(item, identifier=None, accept_missing_identifier=False, raise_if_exists=True)[source]

Helper function to load a record, detect its idenfier and prepare a record item

Parameters:
  • itemstr of incoming item data
  • identifierstr of item identifier (optional)
  • accept_missing_identifierbool of whether a missing identifier in item is valid (typically for a create() method)
  • raise_if_existsbool of whether to check if record already exists
Returns:

tuple of item identifier and item data/payload

create(item)[source]

Create a new item

Parameters:itemdict of new item
Returns:identifier of created item
delete(identifier)[source]

Deletes an existing item

Parameters:identifier – item id
Returns:bool of deletion result
get(identifier, **kwargs)[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)
get_schema(schema_type: pygeoapi.provider.base.SchemaType = <SchemaType.item: 'item'>)[source]

Get provider schema model

Parameters:schema_typeSchemaType of schema (default is ‘item’)
Returns:tuple pair of str of media type and dict of schema (i.e. JSON Schema)
query()[source]

query the provider

Returns:dict of 0..n GeoJSON features or coverage data
update(identifier, item)[source]

Updates an existing item

Parameters:
  • identifier – feature id
  • itemdict of partial or full item
Returns:

bool of update result

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.ProviderInvalidDataError[source]

Bases: pygeoapi.provider.base.ProviderGenericError

provider invalid data error

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.ProviderRequestEntityTooLargeError[source]

Bases: pygeoapi.provider.base.ProviderGenericError

provider request entity too large 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

class pygeoapi.provider.base.SchemaType[source]

Bases: enum.Enum

An enumeration.

CSV provider

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

Bases: pygeoapi.provider.base.BaseProvider

CSV provider

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

Load CSV data

Parameters:
  • offset – 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(offset=0, limit=10, resulttype='results', bbox=[], datetime_=None, properties=[], sortby=[], select_properties=[], skip_geometry=False, q=None, **kwargs)[source]

CSV query

Parameters:
  • offset – 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

class pygeoapi.provider.elasticsearch_.ElasticsearchCatalogueProvider(provider_def)[source]

Bases: pygeoapi.provider.elasticsearch_.ElasticsearchProvider

Elasticsearch Provider

get_fields()[source]

Get provider field information (names, types)

Returns:dict of fields
query(offset=0, limit=10, resulttype='results', bbox=[], datetime_=None, properties=[], sortby=[], select_properties=[], skip_geometry=False, q=None, filterq=None, **kwargs)[source]

query Elasticsearch index

Parameters:
  • offset – 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)
  • filterq – filter object
Returns:

dict of 0..n GeoJSON features

class pygeoapi.provider.elasticsearch_.ElasticsearchProvider(provider_def)[source]

Bases: pygeoapi.provider.base.BaseProvider

Elasticsearch Provider

create(item)[source]

Create a new item

Parameters:itemdict of new item
Returns:identifier of created item
delete(identifier)[source]

Deletes an existing item

Parameters:identifier – item id
Returns:bool of deletion result
esdoc2geojson(doc)[source]

generate GeoJSON dict from ES document

Parameters:docdict of ES document
Returns:GeoJSON dict
get(identifier, **kwargs)[source]

Get ES document 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
mask_prop(property_name)[source]

generate property name based on ES backend setup

Parameters:property_name – property name
Returns:masked property name
query(offset=0, limit=10, resulttype='results', bbox=[], datetime_=None, properties=[], sortby=[], select_properties=[], skip_geometry=False, q=None, filterq=None, **kwargs)[source]

query Elasticsearch index

Parameters:
  • offset – 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)
  • filterq – filter object
Returns:

dict of 0..n GeoJSON features

update(identifier, item)[source]

Updates an existing item

Parameters:
  • identifier – feature id
  • itemdict of partial or full item
Returns:

bool of update result

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(offset=0, limit=10, resulttype='results', bbox=[], datetime_=None, properties=[], sortby=[], select_properties=[], skip_geometry=False, q=None, **kwargs)[source]

query the provider

Parameters:
  • offset – 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(offset=-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 offset 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(offset=-1, limit=-1)[source]

Enable paged access to dataset (OGR Driver-specific)

get_layer()[source]

Gets OGR Layer from opened OGR dataset. When offset 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, skip_geometry=False, crs_transform_spec=None)[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, crs_transform_spec=None, **kwargs)[source]

Get Feature by id

Parameters:
  • identifier – feature id
  • crs_transform_specCrsTransformSpec instance, optional
Returns:

feature collection

get_fields()[source]

Get provider field information (names, types)

Returns:dict of fields
query(offset=0, limit=10, resulttype='results', bbox=[], datetime_=None, properties=[], sortby=[], select_properties=[], skip_geometry=False, q=None, crs_transform_spec=None, **kwargs)[source]

Query OGR source

Parameters:
  • offset – 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)
  • crs_transform_specCrsTransformSpec instance, optional
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(offset=-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(offset=-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.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)

_get_engine_and_table_model()[source]

Create a SQL Alchemy engine for the database and reflect the table model. Use existing versions from stores if available to allow reuse of Engine connection pool and save expensive table reflection.

static _name_for_scalar_relationship(base, local_cls, referred_cls, constraint)[source]

Function used when automapping classes and relationships from database schema and fixes potential naming conflicts.

_reflect_table_model(engine)[source]

Reflect database metadata to create a SQL Alchemy model corresponding to target table. This requires a database query and is expensive to perform.

get(identifier, crs_transform_spec=None, **kwargs)[source]

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

Parameters:
  • identifier – feature id
  • crs_transform_specCrsTransformSpec instance, optional
Returns:

GeoJSON FeatureCollection

get_fields()[source]

Return fields (columns) from PostgreSQL table

Returns:dict of fields
query(offset=0, limit=10, resulttype='results', bbox=[], datetime_=None, properties=[], sortby=[], select_properties=[], skip_geometry=False, q=None, filterq=None, crs_transform_spec=None, **kwargs)[source]

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

Parameters:
  • offset – 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)
  • filterq – CQL query as text string
  • crs_transform_specCrsTransformSpec instance, optional
Returns:

GeoJSON FeatureCollection

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, skip_geometry=False)

Assembles GeoJSON output from DB query

Parameters:
  • row_data – DB row result
  • skip_geometry – whether to skip geometry (default False)
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:dict of single GeoJSON feature
get_fields()[source]
Get fields from sqlite table (columns are field)
Returns:dict of fields
query(offset=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&offset=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:
  • offset – 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