Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • webscraping
  • Beautiful Soup
  • Selenium
  • Scrapy
  • urllib
  • open cv
  • Data analysis
  • Machine learning
  • NLP
  • Deep learning
  • Data Science
  • Interview question
  • ML math
  • ML Projects
  • ML interview
  • DL interview
Open In App
Next Article:
Python | Build a REST API using Flask
Next article icon

Making SOAP API calls using Python

Last Updated : 04 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

SOAP stands for Simple Object Access Protocol, as the name suggests nothing but a protocol for exchanging structured data between nodes. It uses XML instead of JSON.

In this article, we are going to see how to make SOAP API calls using Python. If you want to test out what exactly the payload and response would look like, you can use the below curl command:

CURL Output

Method 1: Using a Request

First, we import requests library, then we define the SOAP URL. 

The next and the most important step is to format the XML body according to the structure provided in the SOAP URL. To know the format, simply visit the SOAP URL and click on CountryISOCode link and format the XML accordingly.

Then you simply prepare the headers and make the POST call.

Code:

Python3

import requests
# SOAP request URL
url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso"
 
# structured XML
payload = """<?xml version=\"1.0\" encoding=\"utf-8\"?>
            <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">
                <soap:Body>
                    <CountryIntPhoneCode xmlns=\"http://www.oorsprong.org/websamples.countryinfo\">
                        <sCountryISOCode>IN</sCountryISOCode>
                    </CountryIntPhoneCode>
                </soap:Body>
            </soap:Envelope>"""
# headers
headers = {
    'Content-Type': 'text/xml; charset=utf-8'
}
# POST request
response = requests.request("POST", url, headers=headers, data=payload)
 
# prints the response
print(response.text)
print(response)
                      
                       

Output:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<m:CountryIntPhoneCodeResponse xmlns:m="http://www.oorsprong.org/websamples.countryinfo">
<m:CountryIntPhoneCodeResult>91</m:CountryIntPhoneCodeResult>
</m:CountryIntPhoneCodeResponse>
</soap:Body>
</soap:Envelope>
<Response [200]>

Method 2: Using Zeep

Now that we have seen how to make SOAP calls with requests, we are going to see how easy it is to make it through Zeep. First, you need to install zeep.

pip3 install zeep

Approach:

  • First, set the WSDL URL. You can get the WSDL URL simply by visiting the base URL and click on Service Description. That will take you to the WSDL URL. The base URL will be service_url and append the service name after the base URL.
  • Next, you need to create a header element. Now, you need to set the header element with method_url and service_url.
  • Now, initialize a zeep client with the WSDL URL.
  • All the setup is done, now you just need to call the zeep service with the service name, here the service name is CountryIntPhoneCode. You need to pass the parameters with the country_code and also pass the header to _soapheaders as a list.
  • Now, this would directly return the phone code of the country.

Code:

Python3

import zeep
 
# set the WSDL URL
wsdl_url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL"
 
# set method URL
method_url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryIntPhoneCode"
 
# set service URL
service_url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso"
 
# create the header element
header = zeep.xsd.Element(
    "Header",
    zeep.xsd.ComplexType(
        [
            zeep.xsd.Element(
                "{http://www.w3.org/2005/08/addressing}Action", zeep.xsd.String()
            ),
            zeep.xsd.Element(
                "{http://www.w3.org/2005/08/addressing}To", zeep.xsd.String()
            ),
        ]
    ),
)
# set the header value from header element
header_value = header(Action=method_url, To=service_url)
 
# initialize zeep client
client = zeep.Client(wsdl=wsdl_url)
 
# set country code for India
country_code = "IN"
 
# make the service call
result = client.service.CountryIntPhoneCode(
    sCountryISOCode=country_code,
    _soapheaders=[header_value]
)
# print the result
print(f"Phone Code for {country_code} is {result}")
 
# set country code for United States
country_code = "US"
 
# make the service call
result = client.service.CountryIntPhoneCode(
    sCountryISOCode=country_code,
    _soapheaders=[header_value]
)
 
# POST request
response = client.service.CountryIntPhoneCode(
    sCountryISOCode=country_code,
    _soapheaders=[header_value]
)
 
# print the result
print(f"Phone Code for {country_code} is {result}")
print(response)
                      
                       

Output:

Phone Code for IN is 91
Phone Code for US is 1
<Response [200]>


Next Article
Python | Build a REST API using Flask
author
debdutgoswami
Improve
Article Tags :
  • Python
  • Python-requests
  • python-utility
Practice Tags :
  • python

Similar Reads

  • How to Make API Call Using Python
    APIs (Application Programming Interfaces) are an essential part of modern software development, allowing different applications to communicate and share data. Python provides a popular library i.e. requests library that simplifies the process of calling API in Python. In this article, we will see ho
    3 min read
  • Save API data into CSV format using Python
    In this article, we are going to see how can we fetch data from API and make a CSV file of it, and then we can perform various stuff on it like applying machine learning model data analysis, etc. Sometimes we want to fetch data from our Database Api and train our machine learning model and it was ve
    6 min read
  • Python | Build a REST API using Flask
    Prerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Fla
    3 min read
  • Python Falcon - API Testing
    Python Falcon is a lightweight and fast web framework designed for building RESTful APIs. When it comes to API testing, Falcon provides a straightforward and efficient way to interact with your API endpoints. In this article, we'll explore three simple examples using Python Falcon: a basic API endpo
    2 min read
  • How to Use ChatGPT API in Python?
    ChatGPT and its inevitable applications. Day by Day everything around us seems to be getting automated by several AI models using different AI and Machine learning techniques and Chatbot with Python , there are numerous uses of Chat GPT and one of its useful applications we will be discussing today.
    6 min read
  • File Sharing App using Python
    Computer Networks is an important topic and to understand the concepts, practical application of the concepts is needed. In this particular article, we will see how to make a simple file-sharing app using Python.  An HTTP Web Server is software that understands URLs (web address) and HTTP (the proto
    4 min read
  • Sending Email using FastAPI Framework in Python
    Before jumping into the topic directly, let's have a small intro about the technologies we are going to use. As the name suggests, we will be using FastAPI, a Python language framework. FastAPI: FastAPI is a python framework to develop REST Apis. It is very easy to build,  high performance, easy to
    3 min read
  • Install Httpx using Python PIP
    When working on the internet or building websites, it's important to have good tools to ask for information. HTTPX is one of these tools, and a lot of people like it because it's fast, flexible, and has many features. This article will explain what HTTPX is and show you simple steps to put it on you
    3 min read
  • How to Use Mega.nz API With Python?
    In this article, we are going to see how to use mega.nz API with Python. MEGA.NZ is End-to-end encrypted and the encryption keys are owned by us. It means that mega.NZ employees won't be able to read personal data. Mega.py is a great Python module for interacting with mega.nz API. It provides easy t
    3 min read
  • Using User Input to Call Functions - Python
    input() function allows dynamic interaction with the program. This input can then be used to call specific functions based on the user's choice . Let’s take a simple example to call function based on user's input . Example: [GFGTABS] Python def add(x, y): return x + y # Add def sub(x, y): return x -
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences