JSON output works in postman but not in python post request - python

I have a python code thats supposed to create a json file that i use as the data in my post requests.
The variable looks like this:
request="""{"QueryString":"{\\"search_type\\":5,\\"project_id_list\\":[\\"1\\"],\\"user_key\\":\\"a\\",\\"options\\":{\\"pagination\\":{\\"page_num\\":1,\\"page_size\\":200},\\"projection\\":{\\"name\\":1},\\"condition_group\\":{\\"conjunction\\":\\"AND\\",\\"conditions\\":[],\\"groups\\":[]},\\"facet\\":{\\"fields\\":[],\\"type\\":0,\\"update_one\\":false},\\"groups\\":[],\\"sort\\":[]},\\"search_types\\":[]}","SearchType":4}"""
When I print the above variable I get the following output:
{"QueryString":"{\"search_type\":5,\"project_id_list\":[\"1\"],\"user_key\":\"a\",\"options\":{\"pagination\":{\"page_num\":1,\"page_size\":200},\"projection\":{\"name\":1},\"condition_group\":{\"conjunction\":\"AND\",\"conditions\":[],\"groups\":[]},\"facet\":{\"fields\":[],\"type\":0,\"update_one\":false},\"groups\":[],\"sort\":[]},\"search_types\":[]}","SearchType":4}
When I use the following output on my postman request it works as I expect it to. But when I use the same variable to send the http request with the following function I get an error.
url = 'www.myurl.com'
body =request
headers = {
'Token': 'sas'}
r = requests.post(url, data=body, headers=headers)
print(r.text) #prints an error {"statusCode":-1,"errMsg":"unexpected end of JSON input"}
Why is my output working on postman but not in python itself?

As the code is working in postman , You can generate python code from postman itself:

Related

Python Post Request Issue, given error 500

body_1 = {"landowner": "asdf#gmail.com","title": report_name,"content": "asdf","project": projectID, }
url_1 = 'http://' + IP + ':8005/projects/notifications/'
response_1 = requests.post(url_1, data=body_1, headers=headers)
For this, I am getting an error 500, when above I have used a similar process to post and it has worked.
I even wrote this code in javascript, and that works but the python equivalent does not.
I tried to add console logs, and everything works up until the response, where it says code 500.
I tried to follow along with javascript as well and try and model it after that too, but that did not work either.
You are getting the error because you are not sending the data as JSON encoded data. When sending an array as data with a request use the json keyword argument. This means your request will look like;
response_1 = requests.post(url_1, json=body_1, headers=headers)
In the example above data= was changed to json=.
By using the json argument the data is encoded to JSON, and the Content-Type header is set to application/json.
Learn more about the json= keyword argument in the requests documentation
If this doesn't fix your issue please add the error output message for the 500 error code.

How can i capture result of requests.POST in Python?

I am quite new to Python and was trying to simulate the result captured when testing API POST requests in Postman. I am basically trying to capture the token generated using the Post method.
I have the following details in Postman which gives me the token details.
Authorization Tab: Type: Basic Auth, Username, Password
Headers Tab: Content-Type: application/x-www-form-urlencoded, Authorization: #This is Auto-Filled
Body Tab: raw: grant_type=client_credentials&scope=read_snfa_unifiedgateway
Now when i run with above details in Postman, it gives me access token in the result but when i use the same details using the following Python Code, i get only <Response [200]> as result for response variable.
import requests
url = 'https://appurl.com/oauth/ls/connect/token'
body = 'grant_type=client_credentials&scope=read_snfa_unifiedgateway'
response = requests.post(
url,
body,
auth=HTTPBasicAuth('my_username', 'my_password'), headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
How can i change the above Python code in such a way that i could get the result in the format i get in Postman as following and then i could use the access_token value in next operation for another POST Method?
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbsdfsdfsdfsdfcsdcsdvarglkwelkrmgmasdmnfjtugnasmdfisdfmmmmpeirhg_-e60s72zgV8Gn2hUiWwlelNQhJongUW6fxwD42c1N5u4R2JJdrj5V_bIwnvY_C_l5wHlIFSQRE1E-5KzP7WG9XjmV9oXRXXGjNhwRqEocGdiEMjcibyiYQNZmG2h-GbsTKvCc21hRNhyRF_y4mdwVUytAXT68TuwZxsTbjUzEvPdwd2JZaFnD9Elo7akSk2ROnRMxN70fsoLzEK71kbzoYkti1jX_V8i_s6K0wmLma-x4nc2kW5mpFM0R9NPqH-kGf-4ZUKim03frifpsGl6Nqo-eN5oZ-b6YgK56mSjxpxQ",
"expires_in": 3600,
"token_type": "Bearer"
}
Use response.json() to get result in dict format. You can use
access_token = response.json()['access_token']

API Post Python

I am trying to make a post request within the Matchbook API.
I have logged in and I got below "Session- Tocken":
{"session-token":"xxxx_b0b8a6f22a82396b6afcfa344f3022","user-id":xx685,"role":"USER"}
However, I am not sure how to make the post request. See below code used:
headers = {"session-token" : "xxxx_b0b8a6f22a82396b6afcfa344f3022"}
r = requests.post('https://api.matchbook.com/edge/rest/reports/v1/offers/current/?odds-type=DECIMAL&exchange-type=binary&currency=EUR, headers = headers')
print r.text
Below is the error message that I got. It does not make sense to me because I logged in successfully and got the above session-token in response.
{"errors":[{"messages":["You are not authorised to access this resource. Login to continue."]}]}
Am I properly indicating the session-token in the header information of the post request?
You need to pass headers argument in post function.
headers = {"session-token" : "xxxx_b0b8a6f22a82396b6afcfa344f3022"}
response = requests.post('https://api.matchbook.com/edge/rest/reports/v1/offers/current/?odds-type=DECIMAL&exchange-type=binary&currency=EUR', headers=headers)
also if you need to get an json response, just call json() function on response variable.
something like response.json()

Making a successful Python HTTP POST Request

I am trying to write a python script that will make a request to a desktop application listening to 8080 port. The below is the code that I use to make the request.
import requests
payload = {"url":"abcdefghiklmnopqrstuvwxyz=",
"password":"qertyuioplkjhgfdsazxvnm=",
"token":"abcdefghijklmn1254786=="}
headers = {'Content-Type':'application/json'}
r = requests.post('http://localhost:9015/login',params = payload, headers=headers)
response = requests.get("http://localhost:9015/login")
print(r.status_code)
After making the request, I get a response code of 401.
However, when I try the same using the Postman app, I get a successful response. The following are the details I give in Postman:
URL: http://localhost:9015/login
METHOD : POST
Headers: Content-Type:application/json
Body: {"url":"abcdefghiklmnopqrstuvwxyz=",
"password":"qertyuioplkjhgfdsazxvnm=",
"token":"abcdefghijklmn1254786=="}
Can I get some suggestions on where I am going wrong with my python script?
You pass params, when you should pass data, or, even better, json for setting Content-Type automatically. So, it should be:
import json
r = requests.post('http://localhost:9015/login', data=json.dumps(payload), headers=headers)
or
r = requests.post('http://localhost:9015/login', json=payload)
(params adds key-value pairs to query parameters in the url)

Python - POST request repsonse and JSON parsing

I´m using Python 2.7.7 to send a post request to a website. Im using the requests module and my code looks like this: (NAME and PASS are substituted)
r = requests.post("http://play.pokemonshowdown.com/action.php", data="act=login&name=NAME&pass=PASS&challengekeyid="+challstrarr[2]+"&challenge="+challstrarr[3])
print(r.text)
print(r.json())
r.text returns just a blank line, r.Json returns this error: "ValueError: No JSON object could be decoded"
The website i´m requesting has the following tutorial:
you'll need to make an HTTP POST request to http://play.pokemonshowdown.com/action.php with the data act=login&name=USERNAME&pass=PASSWORD&challengekeyid=KEYID&challenge=CHALLENGE
Either way, the response will start with ] and be followed by a JSON object which we'll call data."
I´m not sure if the post request response is faulty (and hence the blank line) or if its not faulty and the json parsing is off
You should pass a dictionary object to the post function (the data argument), only in the get method you should pass a query string:
postData = {
#put you post data here
}
r = requests.post("http://play.pokemonshowdown.com/action.php", data=postData)
print(r.text)
print(r.json())

Categories

Resources