Wednesday, 4 January 2012

Python SUDS (SOAP API) full example with WSSE and complex types


I began this task in Perl originally, then decided to switch to Python and have an easier ride. I will upload the Perl example when I sort out a few minor issues with the SOAP::Lite library.

Anyway, in this example, you can specify a WSDL and WSSE (Web Service Security Extensions) username and password (sent in clear text btw), and it will send a SOAP request out and get a sample response back.

I have purposely consumed a service that has some complex types available (basically not just strings and ints). You can see how it is to work with the library and consume your own methods with this example.


Here are some useful things to note
- There have been problems with SUDS generating empty tags for optional properties for complex types. If this is the case, you will receive this error in your SOAP Body's response... "Server was unable to read request. ---> There is an error in the XML document. ---> Instance validation error: '' is not a valid value for PROPERTY_HERE."... To get around this, simply specify those properties (example below)

- client.factory.create() is used to let Python know about the complex types.

- "print client" (Using the example below) will tell you everything you need to know about your service (namespaces, types, methods, properties etc).

- The logger is your friend! Don't be a hero! Start out small and go big! The technique is to analyze the SOAP response and query the errors. If you can get a hold of what the correct SOAP envelope should look like, then compare this against the SOAP request you are sending out. This is the easiest way to solve any problems.

- Coming from a .NET background, I added a service reference and made a simple call with C#. You can then write more code to analyze the SOAP Request, or simply install Fiddler2 (If you haven't got it already, only 600kb and very useful!) to get the correct SOAP envelope to compare against.


Code Snippet
  1. #!/usr/bin/python
  2. #
  3. # Creates a portfolio object using the exacttarget SOAP API. An image must exist at the specified URN
  4. # before alerting the system that the image is ready to be processed,
  5. #
  6. # USAGE:
  7. #    -portfolio <Display Name> <URN> <File Name> <Optional: CustomerKey>
  8. #    -portfoliowsdl <WSDL Address> <WSSE Username> <WSSE Password> <Display Name> <URN> <File Name> <Optional: CustomerKey>
  9. #
  10. #
  11. # Imports
  12. from suds.client import Client
  13. from suds.wsse import *
  14.  
  15. # Logging Options
  16. import logging
  17. logging.basicConfig(level=logging.INFO)
  18. logging.getLogger('suds.client').setLevel(logging.DEBUG)
  19. logging.getLogger('suds.wsdl').setLevel(logging.DEBUG)
  20. logging.getLogger('suds.wsse').setLevel(logging.DEBUG)
  21.  
  22.  
  23. # Define usage options
  24. def printUsage():
  25.     print ""
  26.     print "[USAGE]"
  27.     print "------------------------------------------------------------------------"
  28.     print "    " + sys.argv[0] + " -portfolio <Display Name> <URN> <File Name> <Optional: CustomerKey>"
  29.     print "    " + sys.argv[0] + " -portfoliowsdl <WSDL Address> <WSSE Username> <WSSE Password> <Display Name> <URN> <File Name> <Optional: CustomerKey>"
  30.     print ""
  31.     return
  32.  
  33.  
  34. # Validate argument input
  35. if (len(sys.argv) <= 1):
  36.     print "Invalid usage options..."
  37.     printUsage()
  38.     sys.exit(1)
  39. elif (sys.argv[1] == "-portfolio" and (len(sys.argv) == 5 or len(sys.argv) == 6)):
  40.     print "Setting up a portfolio"
  41. elif (sys.argv[1] == "-portfoliowsdl" and (len(sys.argv) == 8 or len(sys.argv) == 9)):
  42.     print "Setting up a portfolio with WSDL options"
  43. else:
  44.     print "Invalid usage options..."
  45.     printUsage()
  46.     sys.exit(1)
  47.  
  48.  
  49.  
  50. # Setup variables
  51. WSDL_URL = "https://webservice.s4.exacttarget.com/etframework.wsdl"
  52. WSSE_USERNAME = "Username here!"
  53. WSSE_PASSWORD = "Password here!"
  54. PORTFOLIO_DISPLAYNAME = "Test Sean Display Name1"
  55. PORTFOLIO_URN = "http://www.ct4me.net/images/dmbtest.gif"
  56. PORTFOLIO_FILENAME = "dmbtest.gif"
  57. PORTFOLIO_CUSTOMERKEY = ""
  58.  
  59. if (sys.argv[1] == "-portfoliowsdl"):
  60.     WSDL_URL = sys.argv[2]
  61.     WSSE_USERNAME = sys.argv[3]
  62.     WSSE_PASSWORD = sys.argv[4]
  63.     PORTFOLIO_DISPLAYNAME = sys.argv[5]
  64.     PORTFOLIO_URN = sys.argv[6]
  65.     PORTFOLIO_FILENAME = sys.argv[7]
  66.    
  67.     try:
  68.         PORTFOLIO_CUSTOMERKEY = sys.argv[8]
  69.     except:
  70.         print "No Customer key specified. Using default..."
  71. elif (sys.argv[1] == "-portfolio"):
  72.     PORTFOLIO_DISPLAYNAME = sys.argv[2]
  73.     PORTFOLIO_URN = sys.argv[3]
  74.     PORTFOLIO_FILENAME = sys.argv[4]
  75.    
  76.     try:
  77.         PORTFOLIO_CUSTOMERKEY = sys.argv[5]
  78.     except:
  79.         print "No Customer key specified. Using default..."
  80.  
  81.  
  82. # URL Detail
  83. client = Client(WSDL_URL)
  84.  
  85.  
  86. # WSSE Security
  87. security = Security()
  88. token = UsernameToken(WSSE_USERNAME, WSSE_PASSWORD)
  89. security.tokens.append(token)
  90. client.set_options(wsse=security)
  91.  
  92.  
  93. # Build up portfolio
  94. # 'Portfolio' is a complex type... so we use the create method to expose the properties to us. We can then populate the properties as normal.
  95. portfolio = client.factory.create('Portfolio')
  96. portfolio.DisplayName = PORTFOLIO_DISPLAYNAME
  97. portfolio.CustomerKey = PORTFOLIO_CUSTOMERKEY
  98. portfolio.Source = client.factory.create('ResourceSpecification')
  99. portfolio.Source.URN = PORTFOLIO_URN
  100. portfolio.FileName = PORTFOLIO_FILENAME
  101.  
  102.  
  103. # For some reason the SUDS library tends to generate empty SOAP tags for optional properties. Here I have manually specified the defaults here. Just be aware of that!
  104. createOptions = client.factory.create('CreateOptions')
  105. createOptions.RequestType = "Synchronous"
  106. createOptions.QueuePriority= "High"
  107.  
  108.  
  109. # Attach Portfolio to array - Need to set at pos 0, as it returns 1 by default.
  110. apiObject = [client.factory.create('APIObject')]  # Remember [ ], its an array!
  111. apiObject[0] = portfolio
  112.  
  113.  
  114. # Create portfolio
  115. # This method also had 'out' parameters exposed
  116. print client.service.Create(createOptions, apiObject)
  117.  
  118.  
  119. # Uncomment this next line to find out useful information about your service.
  120. # print client
End of Code Snippet

1 comment:

Anonymous said...

Thank you so much! Exactly what I was looking for! :)