Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python + requests, How I send username & password in POST?

I am using python + requests to integrate with qTest REST API. I have a problem on the first step of the login process.

I need to create a POST massage that looks like that:

POST /api/login
Host: nephele.qtestnet.com  
Cache-Control: no-cache  
Content-Type: application/x-www-form-urlencoded  
j_username= maxmccloud%40qasymphony.com&j_password=p@ssw0rd 

I did this on python:

r = requests.post("http://indegy.qtestnet.com/api/login",data="j_username= maxmccloud%40qasymphony.com&j_password=p@ssw0rd")
print r.text

But when I run it it says:

{"message": "Login failed. Invalid username or password."}

like image 534
StasM Avatar asked Oct 21 '15 12:10

StasM


2 Answers

Just pass the username and password in a dictionary to the data argument; requests will then encode the information for you. Use unencoded data, so use @ instead of %40, for example:

data = {
    'j_username': '[email protected]',
    'j_password': 'p@ssw0rd'
}

response = requests.post(
    'http://indegy.qtestnet.com/api/login',
    data=data
)

requests will then encode the dictionary and set the Content-Type header to application/x-www-form-urlencoded as well.

See the More complicated POST requests section in the Quickstart documentation.

like image 174
Martijn Pieters Avatar answered Sep 21 '22 12:09

Martijn Pieters


Try:

import urllib
r = requests.post("http://indegy.qtestnet.com/api/login",data=urllib.urlencode({'j_username': '[email protected]', 'j_password': 'p@ssw0rd'}))
print r.text

Instead of urlencoding data yourself that you are sending to server you should create a dict of data and url encode it using urllib module's urlencode method.

Edit:

As @Martijn suggested, requests does urlencoding itself so you can only do:

r = requests.post("http://indegy.qtestnet.com/api/login",data={'j_username': '[email protected]', 'j_password': 'p@ssw0rd'})
print r.text
like image 30
Muhammad Tahir Avatar answered Sep 19 '22 12:09

Muhammad Tahir