1

I am trying to work through some code to connect to merchantos.com's rest API via Python.

With some research, I have managed to get the GET access working, using the following urllib2 code:

# NOTE:  This api key has been made bogus
lcMOS_APIKey = '07203c82fab495xxxxxxxxxxxxxxxxxxxc2a499c'
# also bogus...
lcMOS_Acct = '98765'
lcBaseURL = 'https://api.merchantos.com/API/Account/' + lcMOS_Acct + '/' 

# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, lcBaseURL, lcMOS_APIKey, 'apikey')
# create "opener" (OpenerDirector instance)    
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)

# use the opener to fetch a URL
#loReturn = opener.open(lcBaseURL + lcURLEnd)  
loReturn = opener.open(lcBaseURL + 'Customer.xml?firstName=Alex')  
lcResponse = loReturn.read()

So, the above successfully pulls data back. I get an XML of the customer record.

Now, what I need to do is change the method so that I can do a PUT (for an update) and a POST (for a create/new).

MerchantOS requires the following for an update:

UPDATE / HTTP PUT To update an existing record/object you do an HTTP PUT request. The put/post data should be an XML block defining the updates to the object. For example to update an Item you would PUT to API/Account/1/Item/2 with an block (1 is the account number and 2 the itemID in this example).

So, for example, I want to do a PUT to update customer ID = 2

I would provide a data reference to an XML block for the

<Customer>
   ..contents omitted here...
</Customer>

And, I am to point it to theURL.

The problems I am facing here are..

  • I do not know where/how to change the method to PUT
  • I need top know how to attach my data block and post it

So, can someone please show me how to adapt the above code for a GET to make a PUT .. as well as a POST (for creating a new record)

Thanks, in advance, for any assistance in this regard.

Scott.

Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71
  • related http://stackoverflow.com/questions/111945/is-there-any-way-to-do-http-put-in-python – jfs Jul 19 '12 at 22:40

1 Answers1

0

You might try cURL instead of urllib. cURL is extremely flexible and addresses your needs:

http://pycurl.sourceforge.net/

Here are two of the options you can set with cURL:

CURLOPT_POST: A parameter set to 1 tells the library to do a regular HTTP post... CURLOPT_POSTFIELDS: The full data to post in a HTTP POST operation...

Justin
  • 207
  • 1
  • 6