Make HTTP Requests using Python + httplib

Python has very good package called httplib, which can send GET,POST,PUT,DELETE methods.

while dealing with REST API's you may want to test the API's.

Examples Here include Registering the User using POST .

POST /user creates user.
GET /user returns the list of users.
GET /user/uid return user details.
PUT /user/uid modifies the user details.
DELETE /user/uid deletes the user from server.

I am providing pseudo code here.

import httplib

# This creates the connection with server running on 5000 port.

h = httplib.HTTPConnection('127.0.0.1', 5000

def do_post():
   '''POST here'''
  hdrs = {'mobile':mobile,'email':email}
  h.request('POST', '/user', None, hdrs)
  resp = h.getresponse()
  print(resp.read())
  print(resp.status) # This prints HTTP status code.
    
def test_get():
  hdrs = {'mobile':mobile,'email':email}
  h.request('GET''/user'None, hdrs)
  resp = h.getresponse()
  print(resp.read())
  print(resp.status) # This prints HTTP status code.

def test_put():
  hdrs = {'mobile':mobile,'email':email}
  #passing known user id 1234 here, you can change for your use case.
  h.request('PUT''/user/1234'None, hdrs)
  resp = h.getresponse()
  print(resp.read())
  print(resp.status) # This prints HTTP status code.


we can further improve this program making multi-threaded/multi-processing and use it to test scalability and performance of your server.

No comments: