Spot any errors? let me know, but Unleash your pedant politely please.

Thursday, 14 March 2013

Python SOAP Request using Requests

If this helps anyone, that would be splendid…



#!/usr/bin/env python
# encoding: utf-8

import requests
from XML import XML
     
request = u"""<?xml version="1.0" encoding="utf-8"?>
              
                  
                  
                      
                          GBP
                          CHF
                      
                  
              """

encoded_request = request.encode('utf-8')

headers = {"Host": "www.webservicex.net",
           "Content-Type": "text/xml; charset=UTF-8",
           "Content-Length": len(encoded_request)}
                          
response = requests.post(url="http://www.webservicex.net/CurrencyConvertor.asmx",
                         headers = headers,
                         data = encoded_request,
                         verify=False)
                         
print unicode(XML(response.text))
    

The XML thingamy used is my own. I've just used it to format the response:



<?xml version="1.0" encoding="utf-8"?>

    
        
            1.4279
        
    



6 comments:

  1. Thank you for this! I've just been tasked with integrating with a SOAP service that Suds and PySimpleSOAP can't cope with and this example has already helped quite a bit. :)

    ReplyDelete
  2. Thanks! This example came in handy

    Although, I found out that I needed to add a "SOAPACTION" to my header ... Any idea why I need to add that and how you are able to get away without having that dictionary item in your header?

    ReplyDelete
    Replies
    1. I have had some services that needed the SOAPACTION. It depends on how the WSDL is written, I think. I don't remember the details, I've only been dealing with JSON for about a year now.

      Delete
  3. Hi thanks for the code
    But I am getting the following error:

    Traceback (most recent call last):
    File "./uc3.py", line 12, in
    from XML import XML
    ImportError: No module named XML


    ReplyDelete
    Replies
    1. Ignore the XML module. I'm using my own hand-rolled module. It's just there to show that the response is in response.text

      Delete