[파이썬] requests SOAP 서비스 요청하기

In this blog post, we will explore how to make SOAP service requests using the Python requests library. SOAP (Simple Object Access Protocol) is a messaging protocol for exchanging structured information in web services.

Installing the Required Libraries

To get started, you will need to install the requests library. You can do this by running the following command in your terminal:

pip install requests

Making a SOAP Request

Next, let’s import the necessary libraries and specify the URL of the SOAP service we want to request:

import requests
from requests import Session
from requests.auth import HTTPBasicAuth

url = "https://example.com/soap-service"

Replace https://example.com/soap-service with the actual URL of the SOAP service you want to interact with.

To send a SOAP request, we need to define the SOAP envelope consisting of the XML request message. We can use Python’s string formatting capabilities to insert dynamic values into the request:

soap_body = '''
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ns="http://example.com/namespace">
    <soap:Header/>
    <soap:Body>
        <ns:SomeRequest>
            <ns:InputParameter>{}</ns:InputParameter>
        </ns:SomeRequest>
    </soap:Body>
</soap:Envelope>
'''

input_value = "Hello, SOAP!"
soap_request = soap_body.format(input_value)

Replace ns:SomeRequest and ns:InputParameter with the appropriate SOAP request elements according to the target service’s documentation.

To send the SOAP request, we can use the Session object from the requests library:

session = Session()
response = session.post(url, data=soap_request, headers={"Content-type": "application/soap+xml"})

The post method is used to send the SOAP request. We pass in the URL, the SOAP request body, and specify the content type as "application/soap+xml".

Handling the SOAP Response

After sending the SOAP request, we can access the response data using the response.content property:

soap_response = response.content

The soap_response variable will contain the XML response message received from the SOAP service.

To extract specific data from the SOAP response, we can use XML parsing libraries such as xml.etree.ElementTree or beautifulsoup4.

Conclusion

In this tutorial, we have seen how to make SOAP service requests in Python using the requests library. We learned how to construct the SOAP envelope, send the request, and handle the response.

SOAP is a widely used protocol for web services interoperability, and with the help of the requests library, we can easily integrate SOAP-based services into our Python applications.

Remember to include necessary authentication and handle any error scenarios as per your specific SOAP service requirements.