how to get response data from a python post request [duplicate] - python-3.x

This question already has answers here:
How to extract HTTP response body from a Python requests call?
(3 answers)
Closed 2 years ago.
I have an openapi3 server running that I'm trying to authenticate with.
I can do it with curl with no problems
curl -k -X POST "https://localhost:8787/api/login/user" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"username\":\"admin\",\"password\":\"admin\"}"
#and i get the token back
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNjEyODY3NDU3LCJleHAiOjE2MTI4NzEwNTd9.9eFgomcpJbinN7L4X1VOHfZGvJeUvHiv6WPjslba1To
but when using python I only get the response code (200) with no data including the token
here is my python script
import requests
import os
url = str(os.environ.get('API_SERVER_URL'))+'login/user'
head = {'accept': 'application/json', 'Content-Type': 'application/json'}
data = {"username": "admin", "password": "admin"} }
response = requests.post(url, json=data, headers=head, verify=False)
print(response)
All I get with this is a 200 response
<Response [200]>

How about getting the content of the response?
For example:
print(response.text)
Or if you expect a JSON:
print(response.json())

Related

error 400 while running PUT request in python

I have a working curl command:
ip_address='<my ip address>'
sessionID='<got from post request metadata>'
curl --insecure --request PUT 'https://'$ip_address'/eds/api/context/records' -H 'Csrf-Token: nocheck' -H 'AuthToken:<token>' -H 'Content-Type: application/json' -H 'Accept: application/json' -d '{"sessionId": "'$session_ID'", "replace":false}'
The python script looks like below:
headers_put = {
'Csrf-Token': 'nocheck',
'AuthToken': '<my token here>',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
url_put = "https://" + ip_address + "/eds/api/context/records"
data = {
"sessionId":"<session id got from POST request metadata>",
"replace":"false"
}
response = requests.put(url_put, headers=headers_put, data=data, verify=False)
print(response)
Error message I get is:
<Response [400]>
b'Bad Request: Invalid Json'
Any idea on what I am doing wrong here? Any help is appreciated!
EDIT:
Can this error cause because of data:
print(data)
{'sessionId': '<session id received from post metadata>', 'replace': 'false'}
Http status 400 means ‘bad request’ as outlined here. You have omitted 1 request header (Csrf-token) in pyScript that was contained in your curl statement. Consider including that and retry the script.
If you still receive an error - you could try and extract (in your script) the actual text or.body of the 4xx response. It may be accessible from the text property of the python response object (you can confirm content-type) using response.apparent_encoding. Best wishes.
I found the solution:
response = requests.put(url_put, headers=headers_put, json=data, verify=False)
instead of data= we have to use json=

python request equivalent of following curl put command

what is python request equivalent of following curl put command.
curl --location --request PUT 'https://xxxx/ejbca/ejbca-rest-api/v1/certificate/CN=CompanyName Issuing CA1 - PoC/69108C91844E53258C646444E0FF0FB797349753/revoke?reason=KEY_COMPROMISE' \
--header 'Content-Type: application/json' \
--data-raw ''
Try:
import requests
headers = {
'Content-Type': 'application/json',
}
params = (
('reason', 'KEY_COMPROMISE'),
)
response = requests.get('https://xxxx/ejbca/ejbca-rest-api/v1/certificate/CN=CompanyName%20Issuing%20CA1%20-%20PoC/69108C91844E53258C646444E0FF0FB797349753/revoke', headers=headers, params=params)
#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.get('https://xxxx/ejbca/ejbca-rest-api/v1/certificate/CN=CompanyName Issuing CA1 - PoC/69108C91844E53258C646444E0FF0FB797349753/revoke?reason=KEY_COMPROMISE', headers=headers)
There is a library which supports these convertion.
pip install uncurl
I was not using correct url pattern, now I am using that I am able to do the needful.
import requests
url = f'https://someserver.dv.local/ejbca/ejbca-rest-api/v1/certificate/CN=SomeCompany%20Name%20Issuing%20CA1%20-%20PoC/8188/revoke?reason=KEY_COMPROMISE'
response = requests.put(
headers={
'content-type': 'application/json'
},
verify=('cacertstruststore.pem'),
cert=('restapi-cert.pem', 'restapi-key.key')
)
json_resp = response.json()
print(json_resp)
Response
{'issuer_dn': 'CN=SomeCompany Name CA1 - PoC', 'serial_number': '8188', 'revocation_reason': 'KEY_COMPROMISE', 'revocation_date': '2020-04-14T18:06:33Z', 'message': 'Successfully revoked', 'revoked': True}

Why does my curl request work and my python3 request not work when calling a webservice?

So I have two (what I think are) identical web service requests...one is from curl which works, and the other is in Python3.
I don't understand the difference between them because the curl one works and returns the expected result, and the Python3 one returns a 500 HTTP status code.
My curl call is as follows:
$ curl -d "{\"Service\": \"Activity\", \"Action\": \"GetDataHistory\",\"Data\": \"{'StartTime':'2019-08-20T13:00:00+00:00', 'EndTime':'2019-08-20T13:10:00+00:00','GameId':'XXXXXXXX-YYYY-ZZZZ-AAAA-BBBBBBBBBBBB'}\"}" -v -H "Content-Type: application/json" -H "cache-control: no-cache" -H "username: someusrname" -H "password: $(echo $vlpasswd)" -X POST -k https://xxx.xxx.xxx.xxx/api/Service/Call | /c/Users/meacct/AppData/Local/Continuum/anaconda3/python -m json.tool
And my Python3 code that "should" do the same thing is here:
import json
import requests as req
import urllib3
endpoint = 'https://xxx.xxx.xxx.xxx/api/Service/Call'
h = {'Content-Type': 'application/json',
'cache-control': 'no-cache',
'username': 'someusrname',
'password':'das-passwd'
}
d = {'Service': 'Activity',
'Action': 'GetDataHistory',
'Data':
{
"StartTime":"2019-08-20T13:00:00+00:00",
"EndTime":"2019-08-20T13:10:00+00:00",
"GameId":"XXXXXXXX-YYYY-ZZZZ-AAAA-BBBBBBBBBBBB"
}
}
# Shut up urllib3's warnings about an invaild SSL Certy.
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
session = req.Session()
try:
res = session.post(url=endpoint, headers=h, data=d, verify=False)
except req.exceptions.SSLError:
print("SSL Error")
print(res.status_code)
res.text
and the output is:
500
'{"Message":"An error has occurred."}'
Why would this be when it looks to be the exact same call?
As the curl request is successful, this indicates that there is something wrong in your Python request, as opposed to the server configuration.
Instead of tracking down the issue, I suggest you try using curlconverter, to generate the Python request directly from the curl request.

cURL : change parse data with list in Python

I have a problem to parse the "data" to data in curl command
curl -H "Content-Type: application/json" -X POST -d '{"data":"traffic cun cun je"}' http://68.xxx.236.113/api/
Above is my curl command. And after I use, https://curl.trillworks.com/ to convert curl command to Python, I got this
import requests
headers = {
'Content-Type': 'application/json',
}
data = '{"data":"traffic cun cun je"}'
response = requests.post('http://68.xxx.236.113/api/', headers=headers, data=data)
The problem is, how can I change the "data":"CHANGE HERE" with the data in a list (text)
Below is my code for the list:
with open('hai.json') as f:
data = json.load(f)
for line in data:
text=line['text']
loc=line['location']
i.append(text)
u.append(loc)

python3 request body with variable

I stuck in my Python3 code when using requests to make HTTP POST requests. I need to put variable "PackageId" inside data and gets error:
{"meta":{"code":4015,"type":"Bad Request","message":"The value of `carrier_code` is invalid."},"data":[]}
My code is:
import requests
import json
PackageId = input("Package number:")
headers = {
'Content-Type': 'application/json',
'Trackingmore-Api-Key': 'MY-API-KEY',
}
data = {
'tracking_number': PackageId,
'carrier_code': 'dpd-poland'
}
request = requests.post('https://api.trackingmore.com/v2/trackings/post', headers=headers, data=data)
The HTTP POST method used is fine, becouse when I hardcode the PackageId in Body, request is successful.
data = '{ "tracking_number": "1234567890", "carrier_code": "dpd-poland" }'
What might be wrong? Please help, I stuck and spend many hours trying to find a problem.
Here is a CURL command I want to reproduce:
curl -XPOST -H 'Content-Type: application/json' -H 'Trackingmore-Api-Key: MY-API-KEY' -d '{ "tracking_number": "01234567890", "carrier_code": "dpd-polska" }' 'https://api.trackingmore.com/v2/trackings/post'
Thanks !!!
You need to convert the data dict to a json string when providing it to post(), it does not happen implicitly:
request = requests.post('https://api.trackingmore.com/v2/trackings/post', headers=headers, data=json.dumps(data))

Resources