12.6. Using REST in Python

Issuing GET Requests
The Python module urllib2 makes reading URLs trivial:

import urllib2

url = 'http://www.acme.com/products/3322'
response = urllib2.urlopen(url).read()

Errors are reported as exceptions (urllib2.HTTPError or urllib2.URLError).

Issuing POST Requests
A POST request is just as easy, simply passing (encoded) request data as an extra parameter to urlopen, thus:

import urllib
import urllib2

url = 'http://www.acme.com/users/details'
params = urllib.urlencode({
  'firstName': 'John',
  'lastName': 'Doe'
response = urllib2.urlopen(url, params).read()

Note that encoding is done using a function from the urllib module.


Andrew said...

Can you post an example that shows a REST request with Authentication.

Dr. M. Elkstein said...

Hi Andrew,

REST with authentication in Python is just like any HTTP request with authentication. You can read about it more in this tutorial.

gokul saran said...
This comment has been removed by the author.
gokul saran said...

Thanks for sharing such informative article on Load runner Automation testing tool. This load testing tool will provide most precise information about the quality of software.
Python training in Chennai