This is a quick tutorial on how to make a restful api using python.
What is web.py ?
According to the official document , web.py is a web framework for Python that is as simple as it is powerful.web.py is in the public domain; you can use it for whatever purpose with absolutely no restrictions.
How to install web.py ?
web.py 0.37 is the latest released version of web.py. You can install it by running:
sudo easy_install web.py
Or using git.
git clone git://github.com/webpy/webpy.git ln -s `pwd`/webpy/web .
Get started
The web service uses
web.py
as a server to run and it generates two url to get the data
http://localhost:8080/users
http://localhost:8080/users/{id}
First, we need to stimulate the data as a xml. Create a file name
user_data.xml
<users> <user id="1" name="Rocky" age="38"/> <user id="2" name="Steve" age="50"/> <user id="3" name="Melinda" age="38"/> </users>
Then, we install the web.py to our python
sudo easy_install web.py
And for the main code, create new file
main.py
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__": app.run()
Finally, we run the command
python main.py
Then open your browser and check the result
http://localhost:8080/users
http://localhost:8080/users/1
http://localhost:8080/users/2
http://localhost:8080/users/3