Lets write some REST web services and play for the first time with python and bottle

In order to start writing the web-services lets take a look at how to setup python on windows.

 

GITHUB : https://github.com/vishwakarmarhl/pythonservices.git

 

Setup Python

Tutorial : https://pypi.python.org/pypi
1. Setup Python
     - Install Python : http://www.python.org/download/
     - Setup path variables
        export PYTHON_HOME=C:\Python27
        export PATH=$PYTHON_HOME:$PYTHON_HOME\Scripts:$PATH
     - Setup MinGW compiler for libraries
        https://gist.github.com/mmlin/1059280
2. Install PIP
    http://www.pip-installer.org/en/latest/installing.html
    $ python ez_setup.py
    $ python get-pip.py
 
3. Libraries
    a. Bottle and Flask
        pip install bottle
        pip install flask
    b. MySQLdb (http://blog.mysqlboy.com/2010/08/installing-mysqldb-python-module.html, http://sourceforge.net/projects/mysql-python/)
        Installed an executable version for windows from sourceforge
        $ easy_install MySQL-python
  
4. Create a database with the *.sql schema file
5. Configure with the db credentials and host name in config.cfg and execute from commandline
        $ py main.py
6.Test GET: http://localhost:8080/users/

Sample REST Service

This is where we can start discussing the web services code segments. We are using the bottle implementation for the service end points.

Considering an example for the GET service here to query all the users in the mysql database table data.user,

# Test using, curl -s http://localhost:8080/users
@route('/users', method='GET')
def getallusers():
try:
mysql_cursor = getDbConnection()
args = 'SELECT `user_id`,`user_name`,`first_name`,`last_name`,`email`,`password`,`organization`,`enabled`,`phone` FROM `data`.`user`';
mysql_cursor.execute(args)
results=mysql_cursor.fetchall()
except MySQLdb.Error, e:
print "MySQL Error %d: %s" % ( e.args[0], e.args[1] )
result = json.dumps(results, default=lambda o: o.__dict__)
return result

The entry point to the code is main.py where DataService.py REST services are being imported and referenced on initialization. 

This is a sample app that can get you quickly started on the bottle based REST web service.

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s