I found some similar solution but it's not working for me. I would like to know the best practice of parser the soap response.
My source code is :
from zeep.transports import Transport
response = transport.post_xml(address, payload, headers)
print(type(response))
print(response.content)
Output:
<class 'requests.models.Response'>
How can I get the **a key** value form the response? which simple and best library I should use.
Thanks in advance.
Using the xml.etree.ElementTree in here
It easily parse content and attribute.
Demo Code
import xml.etree.ElementTree as ET
content = b'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header/><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>UNKNOW_LOCALID</faultstring><detail><ns2:SoapServiceFaultUtilisation xmlns:ns2="http://nps.ideosante.com/"><codeStatus>70</codeStatus><message>Unknown local ID: 1990967085562</message></ns2:SoapServiceFaultUtilisation></detail></soap:Fault></soap:Body></soap:Envelope>'
print(content)
root = ET.fromstring(content)
print(root.find(".//codeStatus").text)
Result
b'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header/><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>UNKNOW_LOCALID</faultstring><detail><ns2:SoapServiceFaultUtilisation xmlns:ns2="http://nps.ideosante.com/"><codeStatus>70</codeStatus><message>Unknown local ID: 1990967085562</message></ns2:SoapServiceFaultUtilisation></detail></soap:Fault></soap:Body></soap:Envelope>'
70
Related
I was using Postman to send post request like on the screenshot
Now I need to implement it in python. This is what i've got for now:
import requests
data = {"sendRequest": {"apiKey": 12345, "field1": "field1value"}}
files = {"attachment": ("file.txt", open("file.txt", "rb"))}
headers = {"Content-type": "multipart/form-data"}
response = requests.post(endpoint, data=data, headers=headers, files=files)
But still it's not working - server doesn't accept it as valid request. I've tried more combinations but without any results and I really couldn't find a solution.
I need this request to be exactly like that one in postman
I finally found a solution. I used MultipartEncoder from requests_toolbelt library.
from requests_toolbelt import MultipartEncoder
import requests
import json
data = {"apiKey": 12345, "field1": "field1value"}}
mp = MultipartEncoder(
fields={
'sendRequest': json.dumps(data), # it is important to convert dict into json
'attachment': ('file.pdf', open('file.pdf', 'rb'), 'multipart/form-data'),
}
)
r = requests.post(ENDPOINT, data=mp, headers={'Content-Type': mp.content_type})
I would like to implement the Speaker Recognition API from Microsoft's Cognitive Services for a Speaker Verification project. I already have a Speaker Recognition API key. I got the sample Python code directly from the documentation (on the bottom of the documentation):
https://westus.dev.cognitive.microsoft.com/docs/services/563309b6778daf02acc0a508/operations/563309b7778daf06340c9652
########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '{subscription key}',
}
params = urllib.parse.urlencode({
})
try:
conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')
conn.request("POST", "/spid/v1.0/verificationProfiles?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################
This is the code sample for the first step, create and save a voice profile.
To conduct Speaker Verification, we need to do 3 steps:
1) Create Profile
2) Create Enrollment
3) Verification
I'm stuck already at the first step now. This is my first time working with APIs in general, so I'm not really sure what parts of the Python code I have to change. I know that I need do insert my API key in 'Ocp-Apim-Subscription-Key' but other than that, what else? For example, if I add my API key in that specific field and let the code run, I received this error message.
b'{"error":{"code":"BadRequest","message":"locale is not specified"}}'
Where do I need to insert the locale ("en-us") for example? It is not really clear to me from the documentation what I need to edit. If you can guide me what I need to insert/add in my API calls I would be very thankful.
Thanks so much in advance!
When you create a Speaker Recognition profile, it has to be linked with a locale, and you specify this locale in the request body. The body should be a JSON object like the following one:
{
"locale":"en-us",
}
For the sample to work, you need to replace "{body}" with the actual body value like this:
conn.request("POST", "/spid/v1.0/verificationProfiles?%s" % params, "{\"locale\":\"en-US\"}", headers)
Trying to get data from the eBay API using GetItem. But requests isn't reading or getting the URL properly, any ideas? Getting this error:
requests.exceptions.MissingSchema: Invalid URL '<urllib.request.Request object at 0x00E86210>': No schema supplied. Perhaps you meant http://<urllib.request.Request object at 0x00E86210>?
I swear I had this code working before but now it's not, so I'm not sure why.
My code:
from urllib import request as urllib
import requests
url = 'https://api.ebay.com/ws/api.dll'
data = '''<?xml version="1.0" encoding="utf-8"?>
<GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
<RequesterCredentials>
<eBayAuthToken>my-auth-token</eBayAuthToken>
</RequesterCredentials>
<ItemID>any-item-id</ItemID>
</GetItemRequest>'''
headers = {
'Content-Type' : 'text/xml',
'X-EBAY-API-COMPATIBILITY-LEVEL' : 719,
'X-EBAY-API-DEV-NAME' : 'dev-name',
'X-EBAY-API-APP-NAME' : 'app-name',
'X-EBAY-API-CERT-NAME' : 'cert-name',
'X-EBAY-API-SITEID' : 3,
'X-EBAY-API-CALL-NAME' : 'GetItem',
}
req = urllib.Request(url, data, headers)
resp = requests.get(req)
content = resp.read()
print(content)
Thank you in advance. Any good reading material for urllib would be great, too.
You are mixing the urllib and the requests library. They are different libraries that can both do HTTP-requests in Python. I'd suggest you use only the requests library.
Remove the line req = urllib.Request(url, data, headers) and replace the resp = ... line with:
r = requests.post(url, data=data, headers=headers)
Print the response body like this:
print(r.text)
Check out the Requests Quickstart here for more examples: https://2.python-requests.org//en/master/user/quickstart/
I am new to python so please be kind! I'm trying to get event data from Mixpanel's export API. I've been able to do this successfully in Talend and Postman but I want to be able to program it in Python.
Try as I might, I'm having no luck. I keep getting a status code of 400.
import requests
import base64
enc = base64.b64encode(b'my-api-secret').decode("ascii")
headers = {f'Authorization': 'Basic {enc}'}
data = {
'from_date': '2019-02-01',
'to_date': '2019-02-03'
}
response = requests.get('https://data.mixpanel.com/api/2.0/export/', data=data, auth=headers)
Any help would be greatly appreciated.
Thanks!
I have a function written in Python for IBM cloud. Which return results as json, for the following python dictionaries:
return {"billing_for_org": output1, "billing_for_org2:": output2}
Is there a way to return this data as a CSV file? So when I invoke the api I am able to download the data as CSV file?
Here is some sample I tested. Let me know if its what you are looking for.
import sys
import csv
import io
def main(dict):
output = io.StringIO()
my_dict = {"billing_for_org": "$100", "billing_for_org2": "$200"}
w = csv.DictWriter(output, my_dict.keys())
w.writeheader()
w.writerow(my_dict)
return {"body": output.getvalue(),
"headers": {'Content-Type': 'text/csv','Content-Disposition':'attachment;filename=myfilename.csv'}}
I am not sure how you are invoking the function as Rest API or Web Action.
I tested above code as web action function and got the result. Please note that extension says http at the end of Url which makes the function to return Non-Default(Json) payloads.
Example Url - https://openwhisk.ng.bluemix.net/api/v1/web/demo_dev/hello-world/helloworld.http
Response Received -
Body:
billing_for_org,billing_for_org2
$100,$200
Headers:
Content-Type →text/csv; charset=UTF-8 Content-Length →45 Connection
→keep-alive Content-Disposition →attachment;filename=myfilename.csv
Reference -
https://console.bluemix.net/docs/openwhisk/openwhisk_webactions.html#openwhisk_webactions.
https://developer.ibm.com/answers/answers/406943/view.html