Search code examples
pythonxmlrestflaskflask-restful

Flask : Processes the XML in GET method


I am trying to create REstful Web Service using Flask. But i am having trouble in processing the xml data in the GET request.

uri="http://127.0.0.1:5000/test/api/getfamilyinfo"

request_body='''
<StayInfo>
    <district>Khurda</district>
    <village>BBSR</village>
    <unit>Hogwarts</unit>
</StayInfo>
'''

body_format = {'Content-Type': 'application/xml'}

requests.get(uri, data = request_body, verify = False, headers = body_format)

I am getting error:

  File &quot;C:\Python27\lib\xml\etree\ElementTree.py&quot;, line 647, in parse
source = open(source, &quot;rb&quot;)
TypeError: coercing to Unicode: need string or buffer, Response found</textarea>

My Code:

@app.route('/test/api/getfamilyinfo', methods=['GET'])
def getfamilyinfo():
    errors = []
    results = {}

    if request.method == "GET":
        try:
            r=request.data

        except Exception,e:
            resp = jsonify({"error": str(e)})
           return resp, status.HTTP_400_BAD_REQUEST

        if r:
            eTree = ElementTree.parse(r) ## The code is breaking here

Kindly help me to understand where i am going wrong. Thanks in advance.


Solution

  • ElementTree.parse() (docs) expects a filename (or file object).

    You want ElementTree.fromstring() (docs).