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}
Related
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=
REST API document
---------------------------------------------------------------
curl --location --request POST 'https://zaya.io/api/v1/links' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Bearer {api_key}' \
--data-urlencode 'url={url}'
-----------------------------------------------------------------
My Code
import requests
api="https://zaya.io/api/v1/links"
API_KEY = "################################################"
data = "https://en.wikipedia.org/wiki/Python_(programming_language)"
headers = {'Authorization': 'Bearer ' + API_KEY}
r = requests.get(api, data=data, headers=headers)
print(response.text)
The error I face:
{"message":"You are not logged in.","status":403}
Mistake 1 You are doing a GET where the document asks you to send a POST.
Mistake 2 The data must be form URL encoded, must be key-value pairs
Mistake 3 You must set the proper Content-Type header
Bigger mistake Do not post your API key on public forums.
The code below works fine, with the above corrections.
import requests
api = "https://zaya.io/api/v1/links"
# Never reveal your API key
API_KEY = "##########################################################"
# Data is URL Form encoded, so it must be key-value pair
data = {"url": "https://en.wikipedia.org/wiki/Python_(programming_language)"}
# Add proper headers
headers = {'Authorization': 'Bearer ' + API_KEY, 'Content-Type': 'application/x-www-form-urlencoded'}
# Most important. CURL says POST, you did GET
r = requests.post(api, data=data, headers=headers)
print(r.text)
# Gives proper response
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.
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)
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))