Interview Questions

Python - Rest Client (GET/POST)

Use the following code to make GET/POST request on a REST interface in python

'''
Created on Aug 8, 2013

@author: Administrator
'
''
import urllib2
import json

class RestClient(object):
    '''
    classdocs
    '
''


    def __init__(self):
        '''
        Constructor
        '
''
       
    def performGET(self,url):
        #url = 'http://www.acme.com/products/3322'
        response = urllib2.urlopen(url).read()
        return response
   
   
    def performPOST(self,url):
             
        jdata = json.dumps({
           "createImage": "true",
           "createdOn": "2013-08-13T14:38:15",
           "modifiedOn": "2013-08-13T14:38:15",
           "name": "DER1902",
           "status": "Active"
        })
       
        req = urllib2.Request(url, jdata, {'Content-Type': 'application/json'})
        f = urllib2.urlopen(req)
        response = f.read()
        print response;
        f.close()
   
   
restClient = RestClient()
url = "http://127.0.0.1:8080/tdd/device/"          
response = restClient.performPOST(url)
print response