API reference

convert(service, target, *, url_index=0) accepts an lxml.etree._Element root element and a pathlib.Path. It validates and renders the evaluator before creating parent directories and replacing the output. It returns the target path. render_evaluator(service, *, url_index=0) returns the same Python source without writing it.

from pathlib import Path
from lxml import etree
from osdd2pygeofilter.converter import convert

parser = etree.XMLParser(resolve_entities=False, load_dtd=False, no_network=True)
service = etree.parse("opensearch.xml", parser).getroot()
convert(service, Path("generated_search.py"))

Only Url elements with type="application/json" and a results relation (including the default relation) are eligible. url_index selects among these URLs in document order. No requests are made during conversion.

Generated API

The module contains OpenSearchEvaluator(Evaluator) and these convenience APIs:

from generated_search import from_cql2_text, from_cql2_json

# For a template https://example.test/search?q={searchTerms}&limit={count?}
query = from_cql2_text("searchTerms = 'ocean & ice' AND count = 10")
assert query == {"q": "ocean & ice", "limit": "10"}
query = from_cql2_json('{"op":"=","args":[{"property":"searchTerms"},"ice"]}')

to_opensearch(root) accepts an existing pygeofilter AST. Query conversion functions return decoded filter parameters without making a request. They accept attribute_map, mapping application property names to placeholder QNames. Each evaluation is independent.

invoke(parameters, defaults=None) merges decoded defaults with supplied parameters and validates them. It expands the original URL_TEMPLATE in place and passes the resulting URL to requests.request(METHOD, url, timeout=30) with a 30-second timeout, without a separate params argument. Filter assignments override defaults; fixed template values cannot be changed. It raises for HTTP errors and returns the response's decoded JSON. invoke_from_cql2_text and invoke_from_cql2_json combine conversion and invocation:

from generated_search import invoke_from_cql2_text

response = invoke_from_cql2_text(
    "text = 'ice'",
    attribute_map={"text": "searchTerms"},
    defaults={"limit": "10"},
)

URL_TEMPLATE preserves the selected OSDD Url/@template exactly as read from XML. Each {name} or {prefix:name?} occurrence is replaced with its percent-encoded value. Optional values that are absent become empty strings; required values must be supplied. Literal paths, separators, fixed query values, existing escapes, repeated keys, and fragments are preserved during expansion. The HTTP client may subsequently normalize the URL for transport and does not send fragment identifiers to the server.

Whole query-value placeholders retain their query-name aliases (q={searchTerms} uses q in the parameter dictionary). A matching Parameter declaration's name takes precedence. For path, composite, or ambiguous repeated query bindings, the placeholder QName is the default dictionary key. For example, /catalog/{eo:platform}/search/{searchTerms} accepts eo:platform and searchTerms, unless Parameter declarations give them other names. Repeated occurrences of a placeholder share a value; any required occurrence makes the value required. These are OpenSearch placeholders, not RFC 6570 expressions such as {?q,count}. At invocation, a small adapter maps OpenSearch placeholders to temporary RFC 6570 variable names. URITemplate performs the actual expansion and UTF-8 percent encoding; other input encodings use urllib.parse.quote before reserved expansion to preserve encoded escapes. URL_TEMPLATE itself stays unchanged.

METHOD comes from the selected URL’s method or Parameters-extension p:method attribute and defaults to GET. Invocation sends the expanded URL with that method; it does not construct a request body.

Input and output encodings use the explicit parameter value, then the first concrete InputEncoding or OutputEncoding declaration, then UTF-8. Encoding placeholders are populated with this selection when omitted. Codec aliases are accepted when they match an advertised encoding. Input encoding controls URL value percent encoding; output encoding controls JSON response decoding unless the response declares an HTTP charset, which takes precedence. Unknown codecs and input characters that cannot be encoded fail before a request is sent.

Quote extension property names in CQL2 text, for example "eo:cloudCover" < 20. Use attribute_map to expose names such as cloud_cover. The prefix must match the description's placeholder; its meaning is resolved using the XML namespace URI, including declarations scoped to a URL.

The generated module requires pygeofilter, pygeoif (also a dependency of pygeofilter), requests, and uritemplate. It does not import osdd2pygeofilter, Jinja2, or lxml at runtime. The generator embeds the validation definitions from its canonical validation source alongside the Jinja2-rendered handlers. Validation fixes take effect in existing modules when you regenerate them.

PARAMETER_OPTIONS maps HTTP query parameter names to tuples of suggested values, for example {"platform": ("Sentinel-1", "Sentinel-2")}. Option labels are omitted. Options alone do not restrict accepted values or imply an enum.

Whenever a handler assigns a parameter value absent from its advertised tuple, it immediately emits a WARNING log record. Listed values, absent parameters, and parameters without options produce no warning. Comparison uses the complete decoded value, including any range, set, or sort syntax. Repeated assignments are checked separately. Computed interval intersections and spatial relation assignments are also checked; copying already checked values while merging predicates does not add warnings. Warnings can therefore be emitted even when a later part of the expression fails. The value remains unchanged and can be submitted by the invocation helpers. Patterns and standard-defined enumerations are still validated at invocation.

Warnings use Python's standard logging module, under the generated module's name. Applications can configure handlers and levels normally; the generated module does not configure logging. Defaults supplied only to invoke are not part of evaluator option checks.

The converter reads namespace scopes, URL offsets and constraint attributes directly from the lxml tree. Pass the OpenSearchDescription root element, using .getroot() when loading an ElementTree. The CLI parses XML with entity resolution, DTD loading and network access disabled. Programmatic callers are responsible for their parser configuration.

See supported queries and constraints for translation limits. Unsupported predicates raise NotImplementedError; invalid values, missing required parameters and conflicting assignments raise ValueError.

Compile an lxml OpenSearch description into a service-specific evaluator.

Only JSON results URLs are eligible. Compilation does not contact the service.

convert(service, target, *, url_index=0)

Write a generated evaluator, creating parents and replacing the target.

Validation and rendering finish before the target is opened. The generated module embeds its validators and requires pygeofilter, pygeoif, requests, and uritemplate at runtime, without importing osdd2pygeofilter.

Parameters:
  • service (_Element) –

    Parsed lxml OpenSearchDescription root element.

  • target (Path) –

    Python module to create or replace.

  • url_index (int, default: 0 ) –

    Zero-based index among application/json results URLs.

Returns:
  • Path –

    The target path.

Raises:
  • ValueError –

    If the selected description cannot be compiled.

  • OSError –

    If the destination cannot be written.

Source code in src/osdd2pygeofilter/converter.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def convert(service: _Element, target: Path, *, url_index: int = 0) -> Path:
    """Write a generated evaluator, creating parents and replacing the target.

    Validation and rendering finish before the target is opened. The generated
    module embeds its validators and requires pygeofilter, pygeoif, requests,
    and uritemplate at runtime, without importing osdd2pygeofilter.

    Args:
        service: Parsed lxml OpenSearchDescription root element.
        target: Python module to create or replace.
        url_index: Zero-based index among application/json results URLs.

    Returns:
        The target path.

    Raises:
        ValueError: If the selected description cannot be compiled.
        OSError: If the destination cannot be written.
    """
    source = render_evaluator(service, url_index=url_index)
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(source, encoding="utf-8")
    return target

render_evaluator(service, *, url_index=0)

Render Python source for a JSON results endpoint without writing files.

Parameters:
  • service (_Element) –

    Parsed lxml OpenSearchDescription root element.

  • url_index (int, default: 0 ) –

    Zero-based index among application/json results URLs.

Raises:
  • ValueError –

    If the URL or its parameter declarations cannot be compiled.

Source code in src/osdd2pygeofilter/converter.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def render_evaluator(service: _Element, *, url_index: int = 0) -> str:
    """Render Python source for a JSON results endpoint without writing files.

    Args:
        service: Parsed lxml OpenSearchDescription root element.
        url_index: Zero-based index among application/json results URLs.

    Raises:
        ValueError: If the URL or its parameter declarations cannot be compiled.
    """
    root = service
    if root.tag != f"{{{CORE}}}OpenSearchDescription":
        raise ValueError("Expected an OpenSearch 1.1 OpenSearchDescription root")
    element = _select_url(root, url_index)
    uri, bindings, fixed = _compile_url(element)
    declarations = {
        name: tuple(item.text or "" for item in root.findall(f"{{{CORE}}}{tag}"))
        for name, tag in (
            ("language", "Language"),
            ("inputEncoding", "InputEncoding"),
            ("outputEncoding", "OutputEncoding"),
        )
    }
    environment = Environment(
        loader=PackageLoader("osdd2pygeofilter", "templates"),
        undefined=StrictUndefined,
        autoescape=select_autoescape(),
        keep_trailing_newline=True,
        trim_blocks=True,
        lstrip_blocks=True,
    )
    environment.filters["python"] = partial(json.dumps, ensure_ascii=False)
    return environment.get_template("evaluator.py.j2").render(
        validation_source=_validation_source(),
        uri=uri,
        method=_http_method(element),
        bindings=bindings,
        fixed=fixed,
        parameter_options={
            parameter.get("name"): tuple(
                option.get("value", "") for option in parameter.findall(f"{{{PARAMETERS}}}Option")
            )
            for parameter in element.findall(f"{{{PARAMETERS}}}Parameter")
            if parameter.find(f"{{{PARAMETERS}}}Option") is not None
        },
        declarations=declarations,
        index_offset=int(element.get("indexOffset", "1")),
        page_offset=int(element.get("pageOffset", "1")),
    )

Generated source quality

Generated modules are formatted for the project's 100-column Ruff configuration and checked with its strict mypy and Bandit settings. Run hatch run dev:generated-check to verify representative outputs, including empty bindings, empty metadata maps, and escaped option values. This check is included in the development quality and check commands.

The emitted source has typed parameter metadata and a recursive JSONValue alias for decoded JSON responses (objects, arrays, scalars, or null). The alias expresses JSON syntax, not a service-specific response schema. Invocation validates values returned across the HTTP client's untyped JSON boundary.

Pygeofilter 0.4.0 does not ship a py.typed marker. The template documents narrow import-untyped exceptions for its imports and a misc exception for inheriting its untyped evaluator. A typed handler-registration adapter preserves method signatures; evaluator results are checked before exposing parameter dictionaries. @_handle calls the original handle decorator to register each function, then returns that same function with its generic callable type preserved. The leading underscore marks this as an internal helper; it does not change dispatch behavior. Using the untyped upstream decorator directly would erase handler signatures and trigger strict mypy's untyped-decorator errors. No host-wide mypy override is needed. Revisit these dependency exceptions when upgrading to a pygeofilter release that publishes typing metadata.