Search code examples
c#aws-lambdasoapserverless

Call soap from aws lambda in C#


I’m new on serverless lambda functions and I have deployed a simple soap api by using C# and I want to know how to call it from a lambda function. In VS you add the reference but what about lambda? I can’t figure out the option

I’ve tried to add the reference with no luck


Solution

  • There isn't a pre-scaffolded method to interact with a SOAP service using a Lambda function. You'd need to handle it "manually" by creating the XML input, sending it through an HTTP request, and then parsing the response.

    Here's a sample using Python, but you can achieve this in any programming language that Lambda supports:

    import json
    import requests
    from datetime import datetime, timedelta
    from xml.dom import minidom
    
    import os
    
    url = os.environ['SERVICE_URL']
    
    query_service_template = """
        <?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
        \t<soap:Body>
        \t\t<SimpleQuery xmlns="http://example.ws.localhost/">
        \t\t\t<m_field>%s</m_field>
        \t\t</SimpleQuery>
        \t</soap:Body>
        </soap:Envelope>
        """
    
    def build_body(field):
      body = query_service_template % (field)
      body = body.replace("\n", "")
      return body.encode('utf-8')
    
    def build_headers(request):
      return {
        "Content-Type": "text/xml; charset=utf-8",
        "Content-Length": str(len(request))
      }    
    
    def extract_data_from_xml(response_body):
      xmldoc = minidom.parseString(response_body)
      outputField = xmldoc.getElementsByTagName('outputField').item(0).firstChild
      
      return {
        'outputField': outputField,
      }
      
    def lambda_handler(event, context):
      # Build request
      request = build_body(event['input_field'])
      
      # Build session
      session = requests.session()
      session.headers = build_headers(request)
      
      # Post request
      response = session.post(url=url, data=request, verify=True)
      
      # Extract data from response
      
      data = extract_data_from_xml(str(response.content, "UTF-8"))
      
      return data