Reputation: 3494
There's an API that I am experimenting with that outputs XML.
Could anyone tell me if I have something wrong my code to parse the API response or is it a problem with the API itself?
I can use a put
command with this:
import requests
import xml
from xml.etree import ElementTree
response = requests.post("https://openadrtester.herokuapp.com/api/v1/cpp/senorio/three")
string_xml = response.content
tree = xml.etree.ElementTree.fromstring(string_xml)
xml.etree.ElementTree.dump(tree)
But it will error out on:
Traceback (most recent call last):
File "C:\Users\bbartling\OneDrive - Slipstream\Desktop\myAPI\tut\test.py", line 7, in <module>
tree = xml.etree.ElementTree.fromstring(string_xml)
File "C:\Users\bbartling\AppData\Local\Programs\Python\Python37\lib\xml\etree\ElementTree.py", line 1315, in XML
parser.feed(text)
File "<string>", line None
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 0
XML is also viewable through the browser on a get request:
https://openadrtester.herokuapp.com/
Upvotes: 1
Views: 649
Reputation: 195408
The data is not XML, but Json (parse it with .json()
method, then access like normal python structure):
import json
import requests
response = requests.post("https://openadrtester.herokuapp.com/api/v1/cpp/senorio/three")
data = response.json()
print(json.dumps(data, indent=4))
Prints:
{
"notification": "True",
"startTime": "2:00PM",
"duration": "6 Hours",
"randomization": "None",
"rampUp": "None",
"recovery": "None",
"numberOfSignals": "2",
"signalNameSimple": [
{
"signalType": "level",
"units": "None",
"numberOfIntervals": "None",
"intervalDuration": "None",
"typicalIntervalValues": "1,2,1",
"signalTarget": "None"
}
],
"signalNameElectricityPrice": [
{
"signalType": "price",
"units": "USD per kWh",
"numberOfIntervals": "3",
"intervalDuration": "1 hour,4 hour,1 hour",
"typicalIntervalValues": "$0.50,$0.75,$0.50",
"signalTarget": "None"
}
]
}
EDIT: To modify request header to obtain XML:
import requests
response = requests.post("https://openadrtester.herokuapp.com/api/v1/cpp/senorio/three", headers={'Accept': 'application/xml'})
print(response.text)
Prints:
<?xml version="1.0" ?><response><notification>True</notification><startTime>2:00PM</startTime><duration>6 Hours</duration><randomization>None</randomization><rampUp>None</rampUp><recovery>None</recovery><numberOfSignals>2</numberOfSignals><signalNameSimple><signalType>level</signalType><units>None</units><numberOfIntervals>None</numberOfIntervals><intervalDuration>None</intervalDuration><typicalIntervalValues>1,2,1</typicalIntervalValues><signalTarget>None</signalTarget></signalNameSimple><signalNameElectricityPrice><signalType>price</signalType><units>USD per kWh</units><numberOfIntervals>3</numberOfIntervals><intervalDuration>1 hour,4 hour,1 hour</intervalDuration><typicalIntervalValues>$0.50,$0.75,$0.50</typicalIntervalValues><signalTarget>None</signalTarget></signalNameElectricityPrice></response>
Upvotes: 2