How to send HTTP request in python?

In this article, we will show you how to send HTTP request in python.

First Create a Http Request Utility Class: http_client.py which we can be useful in any project.

import urllib.request as http
import urllib
import json

def post(url,*positional_params,**keyword_parameters):
   
    if('url_param' in keyword_parameters):
        req = http.Request(url+"?"+urllib.urlencode(keyword_parameters['url_param']))
    else:
        req = http.Request(url)

    if('params' in keyword_parameters):
        req.add_data(json.dumps(keyword_parameters['params']))

    if('header' in keyword_parameters):
        for key,value in (keyword_parameters['header']).iteritems():
            req.add_header(key,value)

    r = http.urlopen(req)
    return r.read()

def get(url,*positional_params,**keyword_parameters):

    if('params' in keyword_parameters):
        req = http.Request(url+"?"+urllib.urlencode(keyword_parameters['params']))
    else:
        req = http.Request(url)

    if('header' in keyword_parameters):
        for key,value in (keyword_parameters['header']).iteritems():
            req.add_header(key,value)

    r = http.urlopen(req)
    return r.read()

Import created class in script.

import http_client as request

Send GET Request Without any params

url = 'http://rangoli.finalhints.com'
request.get(url+'/category')

Send GET Request With Query Parameters

request.get(url+'/category',params={'search':'Amit Bhoraniya'})

Send GET Request With Custom Header

request.get(url+'/category',params={'search':'Amit Bhoraniya'},header={'content-type':'application/json'})

 

For More Details and Example can be downloaded from : Github

Leave a Reply

Your email address will not be published. Required fields are marked *