dreamsys software

Python Scripting Tutorial

Create a simple REST web service with Python

This is a quick tutorial on how to create a simple RESTful web service using python.

The rest service uses web.py to create a server and it will have two URLs, one for accessing all users and one for accessing individual users:


First you will want to install web.py if you don't have it already.

sudo easy_install web.py

Here is the XML file we will serve up.

    <user id="1" name="Rocky" age="38"/>
    <user id="2" name="Steve" age="50"/>
    <user id="3" name="Melinda" age="38"/>

The code for the rest server is very simple:

#!/usr/bin/env python
import web
import xml.etree.ElementTree as ET

tree = ET.parse('user_data.xml')
root = tree.getroot()

urls = (
    '/users', 'list_users',
    '/users/(.*)', 'get_user'

app = web.application(urls, globals())

class list_users:        
    def GET(self):
	output = 'users:[';
	for child in root:
                print 'child', child.tag, child.attrib
                output += str(child.attrib) + ','
	output += ']';
        return output

class get_user:
    def GET(self, user):
	for child in root:
		if child.attrib['id'] == user:
		    return str(child.attrib)

if _name_ == "_main_":

To run your service, simply run:


This creates a web server on port 8080 to serve up the requests. This service returns JSON responses, you can use any of the following URLs to see an example:


Prev (Lists & Maps) | Next (Shell)

Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6