[Python-Webservice]: How to return and consume on XML format on Flask


I am currently creating a RESTful webservice in python utilizing flask. Now on the client side that will use / implement the webservice APIs, I want to get the output in XML (or JSON) format. Do you have any ideas on how to do this? I already tried jsonify but no success. Also, i prefer an XML format in output, but again, I don't know how to do it. So I hope someone can give me ideas.

Below are dummy code snippets to hopefully clarify my question:

/*** webservice ***/
from flask import Flask, jsonify
app = Flask(__name__)

def hello_world():
   return jsonify(message = "hello world!")

if __name__ == "__main__":

/*** client code ***/
import urllib2
server = "http://localhost:5000/"
req = urllib2.Request(server)
# req has no data at all :(

Hoping to receive feedback. Than=ks in advance

3/23/2012 11:57:49 AM

Accepted Answer

The server code runs fine. You should test it with a normal web browser and you will see the json response. Your client code isn't complet. There my correction:

import urllib2
server = "http://localhost:5000/"
req = urllib2.Request(server)
response = urllib2.urlopen(req)
print response.read()

A better way to do http requests in python is to use the requests module which provides a very simple but very powerful api.

import requests
res = requests.get("http://localhost:5000/")
print res.text

To build xml response I would recommend lxml with his cool etree modul. There is also a etree modul in the standart lib under xml.etree.

3/23/2012 12:23:31 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow