Wednesday, July 12, 2017

How to test POST call using Python?

I got into a situation recently where I needed to test if my POST function was indeed working.

Its easy to test GET method . You just visit the URL and that's it . But for POST, you an use PlugIns.

But unfortunately I can't do that , because my browser (admin restrictions ) doesn't allow me to install plugins . Fortunately if you have Python , you can easily do that .

The request module is a handy module when it comes to testing web responses etc. It also has support for POST methods. You can literally fill a form using this . Let's test our url .

This is our POST method. (Its a Flask code).

@app.route('/method', methods=['GET', 'POST'])
def method_used():
    if request.method == 'GET':
        return "Method used: %s" % request.method
    else:
        return "You are using POST"

So if its a GET method, the response we expect is Method used: GET . And if its a POST method, we expect "You are using POST"

Now lets bring out the request module. I have run the statements using the Python IDLE (2.7.11)


>>> import requests
>>> r = requests.post(url='http://127.0.0.1:5000/method')
>>> r.content
'You are using POST'

And there we have it. Our expected response .