client = Client('https://www.example.com/exampleapi')
result = client.service.GetUser(123) # request user with ID 123

name = result['Username']

SOAP 調用的圖表如下所示:

<?xml version="1.0"?>
<soap:Envelope xmlns:soap="https://www.w3.org/2003/05/soap-envelope">
<soap:Header>
</soap:Header>
<soap:Body>
<m:GetUser>
<m:UserId>123</m:UserId>
</m:GetUser>
</soap:Body>
</soap:Envelope>

返回的 SOAP 消息看起來像這樣。

<?xml version="1.0"?>

<soap:Envelope
xmlns:soap="https://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="https://www.w3.org/2003/05/soap-encoding">

<soap:Body>
<m:GetUserResponse>
<m:Username>Tony Stark</m:Username>
</m:GetUserResponse>
</soap:Body>

</soap:Envelope>

如果您使用 HTTP 請求而不是庫來進行所有 SOAP API 調用,它可能看起來像這樣:

import requests
req_headers = {"content-type": "text/xml"}
req_body = "<?xml version=\"1.0\"?>"
req_body += "<soap:Envelope xmlns:soap=\"https://www.w3.org/2003/05/soap-envelope\">"
req_body += "<soap:Header></soap:Header>"
req_body += "<soap:Body>"
req_body += "<m:GetUser>"
req_body += "<m:UserId>123</m:UserId>"
req_body += "</m:GetUser>"
req_body += "v/soap:Body>"
req_body += "</soap:Envelope>"
response = requests.post(
"https://www.example.com/exampleapi",
data=req_body,
headers=req_headers
)

SOAP 消息的內容

這些 SOAP API 請求為您提供了預期格式的示例。讓我們花點時間看看每個組件。

soap:Envelope

SOAP 使用 XML,但它需要一種方法來區分資產和其他 XML 文檔。soap:Envelope表示 XML 是 SOAP。soap:Envelope標簽還需要一個 Namespace 屬性。它還可以包含一個encodingStyle屬性。所有其他 SOAP 組件都在信封內返回。

soap:Header

SOAP 中的標頭是可選的,但您可以使用 通過 SOAP 模塊擴展 SOAP 的可擴展性soap:Header。這些模塊可以是可選的,也可以是必需的。如果它們是必需的,mustUnderstand則必須將屬性設置為 true。

soap:Body

SOAP 響應的大部分內容將包裝在soap:Body標簽內。可以使用命名空間自定義此響應,但這不是必須的。默認情況下,soap:Body將返回過程的名稱、參數和任何返回的數據。

soap:Fault

soap:Fault標簽返回任何錯誤。SOAP 中的錯誤代碼的一些示例包括:

SOAP 與 REST

REST SOAP 有很多共同點。但是,它們之間存在根本差異。了解SOAP 和 REST之間的相似之處和差異將使您更好地理解每種架構。它還應該幫助您了解何時使用REST 而不是 SOAP,反之亦然。

SOAP 和 REST 之間最大的區別在于 SOAP 高度結構化,而REST 和 RESTful API更加靈活。

肥皂與休息

肥皂休息
基于 XML 的消息協議建筑風格的協議
使用 WSDL 進行通信使用 XML 和 JSON 進行通信
結果無法被人類閱讀結果易于理解
使用 HTTP 進行傳輸,但可以傳輸僅通過 HTTP
也可以使用 FTP 或 SMTP
難以用 JavaScript 實現易于在 JavaScript 中使用
性能不如 REST比 SOAP 更高效

POST /Quotation HTTP/1.0
Host: www.xyz.org
Content-Type: text/xml; charset = utf-8
Content-Length: nnn

<?xml version = “1.0”?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV = “http://www.w3.org/2001/12/soap-envelope”
SOAP-ENV:encodingStyle = “http://www.w3.org/2001/12/soap-encoding”>

<SOAP-ENV:Body xmlns:m = “http://www.xyz.org/quotations”>
<m:GetQuotation>
<m:QuotationsName>MiscroSoft</m:QuotationsName>
</m:GetQuotation>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

如您所見,此 SOAP API 調用向/Quotation網站端點發出 POST 請求xyz.org。它還指定了它正在使用的 HTTP 版本以及它期望的響應格式。

這還應該能讓您了解 SOAP API 的可能應用。例如,由于您只接受使用字符集 UTF-8 的 XML 結果,因此您可以自動阻止和阻止所有有細微變化的結果。SOAP API 的用途可能有限且非常具體,但仍然值得您熟悉它,將其納入您的工具包中。

如何使用 Python 調用 SOAP API

現在,讓我們看看 SOAP API 的實際應用。我們將編寫一個 Python 腳本,該腳本將使用該requests庫調用 SOAP API。首先,打開您選擇的文本編輯器并輸入以下代碼:

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)

此代碼首先導入requests庫。然后定義 SOAP URL。不過,以下部分是最重要的,因為它使用標簽指定 SOAP API 格式soap:Body

最后但同樣重要的一點是,Python 腳本在 JSON 中定義標題。

保存該文件并運行它。你應到如下結果:

<?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]>

方法 2:使用 Zeep 在 Python 中調用 SOAP API

最后,我們將介紹另一種在 Python 中調用 SOAP API 的方法的示例。這次我們將使用 Zeep 庫。

首先確保您已安裝 Zeep。

Pip3 install Zeep

安裝 Zeep 后,在文本編輯器中創建一個新文件并輸入以下代碼。

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)

使用 Zeep 庫,您可以輕松獲取任意多個國家的國家電話代碼。然后,它將國家代碼和電話代碼插入到句子“{country_code} 的電話代碼是 {result}”中。”

一旦運行新的 Python 腳本,您應該會得到如下結果。

Phone Code for IN is 91
Phone Code for US is 1

最后的想法:使用 Python 調用 SOAP API

正如我們所見,SOAP API 依然活躍。開發人員仍然需要強類型、安全的事務。它們可能并不常見,但許多傳統產品和服務仍然圍繞 SOAP API 構建。即使不是這樣,了解 SOAP API 在 API 的廣泛采用中所發揮的作用仍然是值得的。

在本文中,我們向您介紹了 SOAP API 格式,并展示了與其他協議(如 REST)的一些比較。然后,我們最后向您展示了如何在 Python 中使用 SOAP API,以便您可以親自嘗試一下。

文章來源:How To Call A SOAP API Using Python

上一篇:

使用功能標記增強API穩定性

下一篇:

使用TypeScript、PostgreSQL與Prisma構建后端:REST API、數據驗證與測試
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費