1

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__)

@app.route("/")
def hello_world():
   return jsonify(message = "hello world!")

if __name__ == "__main__":
   app.run()

/*** 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

1
  • 2
    Suggestion: use Requests instead of urllib2, the API is much nicer. Mar 23, 2012 at 13:48

1 Answer 1

0

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.

2
  • thanks Jarus... I am quite familiar with lxml and use it on outputting text files. But how will I do this in rest API? should I convert the return to lxml format? Mar 23, 2012 at 15:21
  • I would use JSON because it is also very poweful and in my eyes much cleaner than XML. If you want to use lxml than convert your etree to a xml string and return this by your view function.
    – Jarus
    Mar 24, 2012 at 0:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.