Python requests – HTTP library. Examples

If you need to send some HTTP requests and that requires additional processing on your side maybe it’d be better to draft some script. If you happen to know python then you can try its Requests library. Some simple snippets that can be used are placed further.

Set up a session

import requests
from requests import Request, Session
from requests.auth import HTTPBasicAuth

s = requests.Session()

Send POST request:

registrationData = {'registrationCode' :registrationCode ,'customerReference': customerRefNo} + '/customer-account/register',headers = headers, data = registrationData)

Just add required headers e.g

headers = {
 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36'

Send POST with json data

authorisationPayload = {"personRoles":[{"role":"Owner","personId":userId}],
 ["Full permissions","Amend ","No access - cs","No access - cs agree"],
 "personId":userId}]} + '/organisation/' +str(businessID),headers = headers, json = authorisationPayload)

Dealing with Cross-site request forgery

If we have XSRF token added to requests we need to extract it.

def getXsrf(cookies):
    for cookie in s.cookies:
       if =='XSRF-TOKEN':
          return cookie.value

and add it to our headers

xsrf = getXsrf(s.cookies)
 headers['X-XSRF-TOKEN'] = xsrf

Extract data from Json response:

 if ( ra.status_code == 200 ):
   organisationID = ra.json()['_data'][0]['id'] 

In case of unverified HTTPS requests we can suppress warnings (if we really want it) :

from requests.packages.urllib3.exceptions import InsecureRequestWarning

We also probably need to add to our request this parameter  verify=False
to skip verification of HTTPS certificate. Use it if needed of course.

Python requests – HTTP library. Examples

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s