GET/POST to a URL in Python

A relatively simple and straightforward way to post information to a server using Python.

import urllib

# Tries to open the url with the params through the method specified
def fetch_url(url, params, method):
  params = urllib.urlencode(params)
  if method=="GET":
    f = urllib.urlopen(url+"?"+params)
  else:
    # Usually a POST
    f = urllib.urlopen(url, params)
  return (f.read(), f.code)

url = "http://google.com"
method = "POST"
params = {"Param1": "Value1"}

# Fetch the content and response code
[content, response_code] = fetch_url(url, params, method)

# Check if the server responded with a success code (200)
if (response_code == 200):
  print content
else:
  print response_code

2 thoughts on “GET/POST to a URL in Python

  1. Great post. Simple and it works. This very simple code is useful if you have a Linux machine trying to update data on Windows machine you can use OData as your Rest Web service. This is great for multiple environment situations.

  2. how can i try it in django it raises error “fetch_url() takes exactly 3 arguments (1 given)”

Comments are closed.