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.

3 comments:

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

    ReplyDelete
  2. Hi Andrew,

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

    ReplyDelete
  3. Hi ,

    I am able to successfully post a request to a RESTful Web service, but my requirement also requires a search filter in the request body.can you pls help

    ReplyDelete