Mouser Cart API Request
Question: I don't know if I'm going to post it here but I am trying to request to the
Mouser Cart API using python, and the suds library

    
    
    def updateCart():
    url = "https://mews.mouser.com/cartservice.asmx?op=UpdateCart&wsdl"
    client = Client(url)
    xmlns = Attribute("xmlns", "http://tempuri.org/XMLSchema.xsd")
    xmlnsXSD = Attribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema")
    xmlnsXSI = Attribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
    cartGUID = Attribute("CartGUID", "")
    requestor = Attribute("Requestor", "richeve")
    
    cartMessage = Element("CartMessage") \
        .append(xmlns) \
        .append(xmlnsXSD) \
        .append(xmlnsXSI) \
        .append(cartGUID)\
        .append(requestor)
    
    partNumber = Attribute("MouserPartNumber", "941-CCS050M12CM2")
    quantity = Attribute("Quantity", "5")
    cartItem = Element("CartItem").append(partNumber).append(quantity)
    
    cartMessage.append(cartItem)
    
    xmlCartMessage = Element("xmlCartMessage").append(cartMessage)
    
    result = client.service.UpdateCart(xmlCartMessage)
    print result
    print client
    return True
    

The problem with this is that I always get operation timed out. I don't know
if their API or server is malfunctioning. Or I am missing something in my
code.


Answer: I just fought the python <-> Mouser cart API battle and won today. Here is
what I learned.

  1. The timeout is caused by an incorrect endpoint at the bottom of the WSDL. It specifies port 9001, but there is nothing listening there. Overriding the suds client location to remove the port specification makes it work.
    
        url = 'https://mews.mouser.com/cartservice.asmx?WSDL'
    location = 'https://mews.mouser.com/cartservice.asmx'
    client = Client(url, location=location, cache=None)
    

  2. `client.service.UpdateCart()` wants a _string_ XML document. This is what worked for me:
    
        xmlCartMessage = Document()
    xmlCartMessage.append(cartMessage)
    result = client.service.UpdateCart(xmlCartMessage.plain())
    

  3. The response from Mouser is also text—a `suds.sax.text.Text` XML fragment. See <https://lists.fedoraproject.org/pipermail/suds/2011-October/001537.html> for a description of this behavior. I used <https://github.com/martinblech/xmltodict> to wrangle it into a dict.
    
        import xmltodict
    d = xmltodict.parse(result)
    

