如何使用Python编写脚本调用SOAP API并转换为REST API?(持有XSD与WSDL文件)
Hey there! I’ve built a few SOAP-to-REST wrappers in Python before, so let’s walk through exactly how to pull this off using your existing WSDL and XSD files. We’ll use battle-tested libraries that handle most of the heavy lifting for you.
1. First: Generate a SOAP Client from Your WSDL
The easiest way to interact with a SOAP API in Python is using zeep—it’s way more reliable than older libraries like suds, and it natively supports WSDL/XSD parsing.
First, install it:
pip install zeep
Next, create a SOAP client instance using your WSDL. If your WSDL is local, just pass the file path (zeep handles file:// URLs automatically):
from zeep import Client # Load your local WSDL file soap_client = Client(wsdl="./path/to/your/service.wsdl") # Optional: If your API requires authentication (e.g., Basic Auth) from requests.auth import HTTPBasicAuth soap_client.transport.session.auth = HTTPBasicAuth("username", "password")
You can test the SOAP client directly to make sure it works:
# Call a sample SOAP method (replace with your actual method name and params) response = soap_client.service.YourSoapMethod(Param1="value1", Param2="value2") print(response)
Zeep automatically parses the XSD definitions, so you don’t have to manually map complex data types—most of the time, it’ll convert Python dicts/objects to SOAP XML and vice versa.
2. Wrap the SOAP Client in a REST API
Now we’ll create a simple REST layer using FastAPI (it’s modern, fast, and auto-generates interactive docs which is a huge plus). Alternatively, you could use Flask if you prefer a more lightweight framework.
First, install FastAPI and the server:
pip install fastapi uvicorn
Here’s a complete wrapper example that exposes a REST endpoint which calls your SOAP API:
from fastapi import FastAPI, HTTPException from zeep import Client, Fault # Initialize FastAPI app app = FastAPI(title="SOAP-to-REST Wrapper", version="1.0") # Initialize SOAP client (same as before) soap_client = Client(wsdl="./path/to/your/service.wsdl") # Example REST endpoint that maps to a SOAP method @app.get("/api/your-service/{param1}") def call_soap_service(param1: str, param2: str): try: # Call the SOAP method with the REST parameters soap_response = soap_client.service.YourSoapMethod(Param1=param1, Param2=param2) # Convert Zeep's response object to a dict for JSON output rest_response = soap_response.__dict__ return {"success": True, "data": rest_response} except Fault as e: # Handle SOAP faults by converting them to HTTP errors raise HTTPException(status_code=400, detail=f"SOAP Error: {e.message}") except Exception as e: raise HTTPException(status_code=500, detail=f"Internal Error: {str(e)}") # Run the server (execute this script directly) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)
3. Handling Complex XSD Types
If your SOAP API uses complex data structures (like nested objects or arrays), Zeep makes this easy too. For example, if you need to pass a nested object to a SOAP method:
# Create a complex type using Zeep's built-in factory complex_type = soap_client.get_type("ns0:YourComplexType") param_object = complex_type(Field1="value1", Field2=["item1", "item2"]) # Pass it to the SOAP method response = soap_client.service.YourComplexMethod(ComplexParam=param_object)
In your REST endpoint, you can accept JSON payloads that map directly to these complex types—FastAPI will automatically parse the JSON into Python dicts, which Zeep can convert to SOAP objects.
4. Testing the REST API
Once you run the script, you can visit http://localhost:8000/docs in your browser to use FastAPI’s interactive docs. You can send test requests and see the responses immediately, which makes debugging a breeze.
Key Tips for Success
- Validate WSDL/XSD: Make sure your WSDL and XSD files are valid (use tools like
zeep --validate ./path/to/wsdlto check for errors). - Handle Namespaces: Zeep handles namespaces automatically, but if you run into issues, you can explicitly reference them using the
ns0:prefix (like in the complex type example above). - Logging: Add logging to track SOAP requests/responses for debugging—Zeep has built-in logging you can enable:
import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("zeep") logger.setLevel(logging.DEBUG)
内容的提问来源于stack exchange,提问作者Pedda Babu Asapu

