A Singapore Government Agency Website

Flatten WSDL for Import

1. Problem statement

APEX does not support importing WSDLs that reference external XML schemas. A WSDL can refer to XSDs or other WSDLs stored in separate files or URLs. APEX expects a single self-contained document — those external references will cause the import to fail.

For example, a WSDL may contain:

<wsdl:types xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:schema targetNamespace="urn:hello:service">
    <xs:import namespace="urn:hello:types" schemaLocation="hello.xsd"/>
  </xs:schema>
</wsdl:types>

APEX would need to fetch hello.xsd to understand the full type definitions, but only the original WSDL is uploaded.

Flattening fetches those dependencies and embeds them into one WSDL. After flattening, upload the generated file to APEX instead. The result may still contain xs:import namespace="..." declarations, but the external schemaLocation attributes are removed and the corresponding schemas are embedded under wsdl:types.

Flattening addresses missing external definitions. It does not guarantee that APEX supports every schema construct in your WSDL. If APEX rejects xs:import declarations even without external locations, the WSDL may use features outside APEX’s supported schema subset.

When you can skip this guide

You can import the WSDL directly into APEX and skip this guide if either condition applies:

  • Your WSDL is already self-contained, with all required WSDL/XSD definitions embedded and no external dependencies to resolve.
  • Your service supports a single-document endpoint such as ?singleWsdl, and the returned document contains all required definitions. For example, use https://example.com/service?singleWsdl instead of https://example.com/service?wsdl, if supported by the server.

The ?singleWsdl parameter is server-specific; adding it to any URL does not guarantee a single-document response. A single downloaded .wsdl file may still reference external XSDs, so check the returned definition before importing it into APEX.

2. Bring your own tool

You may use your own WSDL flattening tool, including tools available online, to produce a self-contained WSDL. This guide does not require or recommend a particular third-party tool. Check that your chosen tool resolves the required dependencies and that its output can be imported by APEX.

If you prefer to use the supplied Python script, follow the steps below.

3. Python script overview

Disclaimer: This script was AI-generated (“vibe coded”) and has only been verified against the common WSDL/XSD patterns covered by its test suite. It is not a general-purpose, standards-complete flattening tool. If your WSDL uses an unlisted or unusual format (see Section 8), the script may fail or produce incorrect output — review the result carefully, or use your own tool (Section 2) instead.

The supplied main.py accepts a WSDL URL or local path and produces a flattened WSDL ready for APEX import. The full script is included in Appendix A for copying or distribution. The accompanying requirements.txt is reproduced in Appendix B.

The workflow is:

  1. Read the root WSDL.
  2. Resolve supported imports/includes recursively.
  3. Embed schemas while preserving their namespaces and schema defaults.
  4. Remove resolved external WSDL/XSD references and xml:base attributes.
  5. Load the generated XML with Zeep while blocking external document reads.
  6. Write the output after successful verification, unless verification was explicitly skipped.

The script does not call the SOAP service. SOAP endpoint addresses remain in the WSDL so APEX can use them after import.

Supported versions

Specification Support
WSDL 1.1 Supported, subject to the limitations below.
SOAP 1.1 bindings in WSDL 1.1 Supported.
SOAP 1.2 bindings in WSDL 1.1 Supported.
WSDL 1.2 drafts / WSDL 2.0 Unsupported.
XML Schema 1.0 Intended schema version.
XML Schema 1.1 Unsupported.

SOAP 1.2 is not WSDL 1.2. A SOAP 1.2 service can still publish a WSDL 1.1 document.

4. Prerequisites

Use Python 3.10 or later, with pip and venv available. Save the supplied main.py and requirements.txt in the same folder, or copy them from Appendices A and B.

The commands below install all Python dependencies. You need access to the package repository during installation and to every WSDL/XSD file or URL referenced by your input.

5. Setup

Open a terminal in the folder containing main.py and requirements.txt, then run the commands for your operating system.

Windows PowerShell

py -3 --version
py -3 -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install -r requirements.txt
python main.py --help

If activation is blocked, use .\.venv\Scripts\python.exe in place of python without activating the environment:

.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe main.py --help

macOS / Linux

python3 --version
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
python main.py --help

Confirm the version printed by the first command is at least 3.10. After setup, use python main.py as shown below. For later sessions, activate the existing .venv again; you do not need to reinstall dependencies each time.

6. Command reference

python main.py WSDL [-o OUTPUT] [--timeout SECONDS] [--header "NAME: VALUE"] [--insecure] [--no-verify]
Argument or option Meaning Default
WSDL Root WSDL URL, local path, or file:// URL. Required. None
-o, --output Destination file. Use - to write XML to standard output. flattened.wsdl
--timeout Timeout passed to each document fetch, in seconds; not an overall run deadline. Use a positive number. 30
--header HTTP header in NAME: VALUE format, such as --header "User-Agent: Mozilla/5.0" or --header "Authorization: Bearer TOKEN". Repeat for multiple headers. No custom headers
--insecure Disable certificate and hostname verification for all HTTPS fetches. Verification enabled
--no-verify Skip the final offline Zeep check. Offline check enabled
-h, --help Display help and exit. —

Custom headers apply to every dependency fetch, including imports on other hosts. Use trusted inputs when supplying credentials; command-line values can appear in shell history or process listings. --insecure disables certificate and hostname checks for all HTTPS fetches and does not fix authorization errors. --no-verify skips only the final Zeep check, not parsing or import restrictions.

Status and error messages go to standard error. XML goes to standard output only with -o -. The process exits with 0 on success and 1 for processing failures; invalid CLI arguments normally produce argparse’s exit code 2.

Quote URLs containing ? or &, and paths containing spaces. Hosts under example.com are placeholders, not live test services.

7. Usage examples

7.1 Flatten a remote source

python main.py "https://example.com/service?wsdl" -o flattened.wsdl

The script downloads the WSDL and resolves supported imports/includes recursively. HTTP and HTTPS URLs are supported. Use the command reference above to add request headers, adjust the timeout, or change verification options if needed.

7.2 Flatten a local file

python main.py "service/hello.wsdl" -o flattened.wsdl

The input can be a relative path, an absolute path, or a file:// URL. Relative imports resolve against the file containing each reference, not the terminal’s working directory. Keep the referenced files in their expected folder structure. A web server is not needed for local files; network access is needed only if they reference remote dependencies.

Both examples write flattened.wsdl in the current working directory. On success, the script reports:

Verified offline with Zeep.
Wrote flattened.wsdl

An existing output file is overwritten after successful processing and verification. Choose a different output filename from the input, and create the destination folder first. Upload the generated WSDL to APEX to confirm it imports successfully.

8. Unsupported scenarios and limitations

Scenario or limit Current behavior / implication
WSDL 1.2 drafts or WSDL 2.0 Rejected. The root must be WSDL 1.1 definitions in http://schemas.xmlsoap.org/wsdl/.
Cross-namespace wsdl:import Rejected. The script does not rewrite component namespaces/QNames to merge different WSDL namespaces.
wsdl:include Not implemented; it is not a WSDL 1.1 feature.
Chameleon XSD includes Rejected when a no-namespace schema would adopt a namespaced includer’s namespace.
xs:redefine or xs:override Rejected.
XSD 1.1 Unsupported. Some indicators are detected, but this is not a complete XSD-version/conformance detector.
Missing location on a WSDL import or schemaLocation on an XSD include Rejected.
XSD import without a location and without an otherwise available namespace Rejected. No namespace-URI discovery or XML Catalog support.
Standalone XSD as the root input Rejected. Start with a WSDL that references it.
DTDs / external entities DTD-bearing documents are rejected; entity expansion is disabled.
Other URL schemes Only HTTP, HTTPS, and file URLs are supported. No FTP or custom loaders.
Missing files, access failures, malformed XML, or namespace mismatches Processing fails. The script does not repair definitions or silently drop failed dependencies.
Duplicate global schema declarations / duplicate merged WSDL components Detected duplicates cause failure. There is no conflict-resolution or renaming strategy.
Multiple schema blocks with the same namespace Produced for includes to preserve source schema defaults. APEX may require a different layout.
Remaining namespace-only xs:import declarations They are intentionally retained. APEX may still reject the output if it does not support import declarations without locations.
WS-Policy, XInclude, vendor-specific external references Not resolved; WSDL/XSD self-containment does not imply all extension resources have been embedded.
Source xml:base attributes Used while resolving dependencies, then stripped from output. Relative URIs inside unresolved policy/extensions may consequently lose their original interpretation.
Browser sessions / advanced authentication No browser cookie/session acquisition, OAuth login flow, NTLM/Kerberos integration, or client-certificate CLI options. Header-based credentials are supported.
Server access policies User-Agent/headers may help, but browser-only challenges or server policies can still block downloads.
Resource limits Each fetched document is limited to 20 MiB. No configurable aggregate byte/document limit or overall deadline; very deep WSDL import chains can hit Python recursion limits.
Caching and aliases Cache lasts only for one flatten call. Distinct URLs/paths or redirect aliases may not deduplicate; no persistent cache or retry/backoff option.
Output handling Existing output can be overwritten; parent directories are not created automatically. Writes are not atomic, so disk/write failures can leave incomplete output.
Verification scope Strict Zeep loading with external reads blocked checks dependency closure and Zeep compatibility, not full W3C validation, APEX compatibility, or live service behavior. Warnings are treated as verification failures.
Portability Source requires Python and compatible dependencies. No standalone executable is supplied, and installed virtual environments are not portable bundles.

The script is a proof-of-concept tool. Passing the offline check is useful evidence, but import the result into APEX before considering the workflow complete.

9. Troubleshooting

Symptom What to check
python or py is not found Install Python; reopen the terminal; check PATH/interpreter selection.
No module named lxml or zeep Activate the correct .venv and run python -m pip install -r requirements.txt.
PowerShell blocks activation Use .venv\Scripts\python.exe directly as shown in setup.
HTTP Error 401 / 403 Check permissions and required headers. If the server rejects Python’s default User-Agent, try --header "User-Agent: Mozilla/5.0". --insecure does not change authorization.
CERTIFICATE_VERIFY_FAILED Check the server certificate, machine trust store, and corporate TLS settings. If acceptable for testing, use --insecure.
Connection refused on localhost Start the local file server, verify its port, and keep its terminal running.
Local dependency not found Check spelling, folder layout, and the location relative to the referencing file. In XML references, prefer forward slashes or a proper file URL over Windows backslashes.
Expected WSDL 1.1 definitions The URL may be returning HTML/login content, an XSD, or a different WSDL version. Inspect the input.
No schema supplied for imported namespace Supply a valid schemaLocation or an inline schema for that namespace.
Offline Zeep check fails Review the reported definition error and unsupported cases. --no-verify can produce diagnostic output, but does not make it valid for APEX import.
Output directory missing Create the parent folder before running the command.

10. Verify the result and import into APEX

After a successful run:

  1. Confirm the output file exists and the command exited successfully.
  2. Check that relevant external schemaLocation attributes, XSD includes, and supported WSDL imports have been resolved.
  3. Import the output into APEX via Publish → Create new SOAP API. Confirm that expected operations and request/response fields are present.
  4. Test actual service calls separately; flattening and offline verification do not contact the SOAP endpoint.

Appendix A. Complete Python script

Disclaimer: AI-generated script, verified only against the common-case test suite in Section 9. Not a complete WSDL/XSD implementation — see Section 8 for known gaps. For WSDLs with an unusual or special format, find your own flattening tool instead of relying on this script as-is.

Save the following as main.py.

"""Flatten WSDL 1.1 and external XSDs; preserve SOAP 1.1/1.2 bindings.

WSDL 1.2 drafts and WSDL 2.0 are unsupported. This POC resolves XSD 1.0
imports and same-namespace includes, and same-namespace WSDL imports.
See README.md for unsupported schema and import cases.
"""
from __future__ import annotations

import argparse
from copy import deepcopy
from io import BytesIO
from pathlib import Path
import re
import ssl
import sys
from uuid import uuid4
from urllib.parse import urljoin, urlparse
from urllib.request import Request, urlopen

from lxml import etree

WSDL = 'http://schemas.xmlsoap.org/wsdl/'
XSD = 'http://www.w3.org/2001/XMLSchema'
XML = 'http://www.w3.org/XML/1998/namespace'
NS = {'wsdl': WSDL, 'xs': XSD}


class FlattenError(ValueError):
    """Input cannot safely be flattened by this implementation."""


def qn(namespace, name):
    return f'{{{namespace}}}{name}'


def detached(element):
    """Keep inherited namespace bindings, including ones used only in QNames."""
    data = etree.tostring(element, encoding='utf-8', with_tail=False)
    # An absent default namespace must not inherit the destination's default.
    if None not in element.nsmap:
        data = re.sub(rb'^<([^\s/>]+)', rb'<\1 xmlns=""', data, count=1)
    return etree.fromstring(data, etree.XMLParser(resolve_entities=False, no_network=True))


class WsdlFlattener:
    def __init__(self, timeout=30, headers=None, insecure=False):
        self.timeout = timeout
        self.headers = headers or {}
        self.ssl_context = ssl.create_default_context()
        if insecure:
            self.ssl_context.check_hostname = False
            self.ssl_context.verify_mode = ssl.CERT_NONE

    def _load(self, location):
        if location not in self.cache:
            if urlparse(location).scheme not in ('http', 'https', 'file'):
                raise FlattenError(f'Unsupported URL scheme: {location}')
            with urlopen(Request(location, headers=self.headers), timeout=self.timeout,
                         context=self.ssl_context) as response:
                data = response.read(20 * 1024 * 1024 + 1)
                final_url = response.geturl()
            if len(data) > 20 * 1024 * 1024:
                raise FlattenError(f'Document exceeds 20 MiB: {location}')
            parser = etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
            root = etree.fromstring(data, parser, base_url=final_url)
            if root.getroottree().docinfo.doctype:
                raise FlattenError(f'DTDs are unsupported: {location}')
            self.cache[location] = root
        return deepcopy(self.cache[location])

    def flatten(self, location):
        self.cache, self.wsdls, self.schemas = {}, set(), set()
        self.pending = []
        self.payloads = {}
        self.components = set()
        location = str(location)
        if Path(location).is_absolute() or not urlparse(location).scheme:
            location = Path(location).expanduser().resolve().as_uri()
        root = self._load(location)
        if root.tag != qn(WSDL, 'definitions'):
            raise FlattenError('Expected a WSDL 1.1 definitions document')
        self.target_namespace = root.get('targetNamespace')
        self.root = root
        self.components = {(e.tag, e.get('name')) for e in root if e.get('name')}
        self.types = root.find(qn(WSDL, 'types'))
        if self.types is None:
            self.types = etree.Element(qn(WSDL, 'types'), nsmap={'xs': XSD})
            root.insert(0, self.types)
        self._wsdl(root, location)
        # The list grows as external schemas are discovered.
        index = 0
        while index < len(self.pending):
            schema, base = self.pending[index]
            self._schema(schema, base)
            index += 1
        available = {s.get('targetNamespace') for s, _ in self.pending}
        declarations = set()
        for schema, _ in self.pending:
            for child in schema:
                if isinstance(child.tag, str) and child.get('name'):
                    # simpleType/complexType share the same XSD symbol space.
                    kind = 'type' if child.tag in (qn(XSD, 'simpleType'), qn(XSD, 'complexType')) else child.tag
                    key = (schema.get('targetNamespace'), kind, child.get('name'))
                    if key in declarations:
                        raise FlattenError(f'Duplicate XSD declaration: {key}')
                    declarations.add(key)
        for schema, _ in self.pending:
            for imp in schema.findall(qn(XSD, 'import')):
                namespace = imp.get('namespace')
                if namespace not in available and namespace != XSD:
                    raise FlattenError(f'No schema supplied for imported namespace {namespace!r}')
        for schema, _ in self.pending:
            self._append_payload(self.types, schema)
        # Keep WSDL's declaration order after merging imported components.
        rank = {qn(WSDL, name): i for i, name in enumerate(
            ('documentation', 'import', 'types', 'message', 'portType', 'binding', 'service'))}
        root[:] = sorted(root, key=lambda e: rank.get(
            self.payloads[e.text].tag if e.tag is etree.Comment and e.text in self.payloads else e.tag, 99))
        # Grafting lxml elements can discard namespace aliases used only inside
        # QName-valued attributes. Insert independent XML serializations instead.
        data = etree.tostring(root, encoding='utf-8')
        for marker, element in self.payloads.items():
            data = data.replace(f'<!--{marker}-->'.encode(), etree.tostring(element, encoding='utf-8', with_tail=False))
        result = etree.fromstring(data, etree.XMLParser(resolve_entities=False, no_network=True))
        # Base URIs are needed while resolving imports, but must not leak into
        # the self-contained output (including bases supplied by source files).
        for element in result.iter():
            element.attrib.pop(qn(XML, 'base'), None)
        return result

    def _append_payload(self, parent, element):
        marker = f'wsdl-flatten-payload-{uuid4().hex}'
        self.payloads[marker] = element
        parent.append(etree.Comment(marker))

    def _wsdl(self, document, location):
        self.wsdls.add(location)
        for schema in document.findall('wsdl:types/xs:schema', NS):
            base = schema.base or location
            copy = detached(schema)
            copy.set(qn(XML, 'base'), base)
            self.pending.append((copy, base))
            schema.getparent().remove(schema)
        for imp in list(document.findall(qn(WSDL, 'import'))):
            href = imp.get('location')
            if not href:
                raise FlattenError('wsdl:import is missing location')
            url = urljoin(imp.base or location, href)
            if url not in self.wsdls:
                imported = self._load(url)
                if imported.tag != qn(WSDL, 'definitions'):
                    raise FlattenError(f'Not a WSDL document: {url}')
                namespace = imported.get('targetNamespace')
                if imp.get('namespace') != namespace:
                    raise FlattenError(f'wsdl:import namespace mismatch: {url}')
                if namespace != self.target_namespace:
                    raise FlattenError('Cross-namespace wsdl:import cannot be safely merged '
                                       'into one WSDL 1.1 definitions element')
                self._wsdl(imported, url)
                for child in imported:
                    if child.tag in {qn(WSDL, n) for n in ('message', 'portType', 'binding', 'service')}:
                        key = (child.tag, child.get('name'))
                        if key in self.components:
                            raise FlattenError(f'Duplicate WSDL component: {child.get("name")}')
                        self.components.add(key)
                        self._append_payload(self.root, detached(child))
            document.remove(imp)

    def _external_schema(self, directive, base, expected_namespace, include=False):
        href = directive.get('schemaLocation')
        if not href:
            if include:
                raise FlattenError('xs:include is missing schemaLocation')
            return
        url = urljoin(directive.base or base, href)
        source = self._load(url)
        if source.tag != qn(XSD, 'schema'):
            raise FlattenError(f'Not an XSD schema: {url}')
        namespace = source.get('targetNamespace')
        if include and namespace is None and expected_namespace is not None:
            raise FlattenError(f'Chameleon include (no targetNamespace) is unsupported: {url}')
        if namespace != expected_namespace:
            raise FlattenError(f'XSD namespace mismatch: {url}: expected '
                               f'{expected_namespace!r}, got {namespace!r}')
        key = (url, namespace)
        if key not in self.schemas:
            self.schemas.add(key)
            # Separate blocks preserve elementFormDefault, attributeFormDefault,
            # and prefix bindings of each source schema, even for xs:include.
            source_base = source.base or url
            source = detached(source)
            source.set(qn(XML, 'base'), source_base)
            self.pending.append((source, source_base))

    def _schema(self, schema, base):
        if schema.get('version', '').startswith('1.1') or schema.get('xpathDefaultNamespace') is not None:
            raise FlattenError('XSD 1.1 is unsupported')
        for directive in list(schema):
            if directive.tag in (qn(XSD, 'redefine'), qn(XSD, 'override')):
                raise FlattenError('xs:redefine and xs:override are unsupported')
            if directive.tag == qn(XSD, 'include'):
                self._external_schema(directive, base, schema.get('targetNamespace'), include=True)
                schema.remove(directive)
            elif directive.tag == qn(XSD, 'import'):
                if directive.get('namespace') == schema.get('targetNamespace'):
                    raise FlattenError('xs:import must refer to a different namespace')
                self._external_schema(directive, base, directive.get('namespace'))
                directive.attrib.pop('schemaLocation', None)


def verify(xml):
    """Load with Zeep while prohibiting every external document read."""
    import warnings
    from zeep import Client, Settings
    from zeep.transports import Transport

    class OfflineTransport(Transport):
        def load(self, url):
            raise FlattenError(f'Output still requires an external document: {url}')

    with warnings.catch_warnings():
        warnings.simplefilter('error')
        return Client(BytesIO(xml), transport=OfflineTransport(), settings=Settings(strict=True))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('wsdl', help='WSDL URL or local path')
    parser.add_argument('-o', '--output', default='flattened.wsdl', help='Output path, or - for stdout')
    parser.add_argument('--timeout', type=float, default=30, help='Timeout per fetch in seconds')
    parser.add_argument('--insecure', action='store_true', help='Disable TLS certificate and hostname verification for all HTTPS fetches')
    parser.add_argument('--header', action='append', default=[], metavar='NAME: VALUE', help='HTTP header for all fetches; repeatable')
    parser.add_argument('--no-verify', action='store_true', help='Skip offline Zeep verification')
    args = parser.parse_args()
    try:
        headers = {}
        for header in args.header:
            name, separator, value = header.partition(':')
            if not separator or not name.strip():
                raise FlattenError('--header must have the form NAME: VALUE')
            headers[name.strip()] = value.strip()
        root = WsdlFlattener(args.timeout, headers, insecure=args.insecure).flatten(args.wsdl)
        xml = etree.tostring(root, encoding='utf-8', xml_declaration=True, pretty_print=True)
        if not args.no_verify:
            verify(xml)
            print('Verified offline with Zeep.', file=sys.stderr)
        if args.output == '-':
            sys.stdout.buffer.write(xml)
        else:
            Path(args.output).write_bytes(xml)
            print(f'Wrote {args.output}', file=sys.stderr)
    except Exception as exc:
        print(f'error: {exc}', file=sys.stderr)
        return 1
    return 0


if __name__ == '__main__':
    sys.exit(main())

Appendix B. Dependency file

Save this as requirements.txt next to main.py.

attrs==26.1.0
certifi==2026.10.23
charset-normalizer==3.5.2
idna==3.20
isodate==0.7.2
lxml==6.1.3
platformdirs==4.12.4 ; python_full_version < '3.11'
platformdirs==4.14.0 ; python_full_version >= '3.11'
requests==2.34.2
requests-file==3.0.1
requests-toolbelt==1.0.0
urllib3==2.8.0
zeep==4.3.3
Chat with me!
Bot Launcher