I have below curl command
file_location='some/path/to/test.csv'
auth_token='my_api_token'
curl --insecure --request POST 'https://<ip_address>/eds/api/table/table_name/changes/addBulk?hasHeader=false' -H 'Csrf-Token: nocheck' -H 'AuthToken:'$auth_token'' -H 'Content-Type: multipart/form-data' --form 'data=#'$file_location'
The data in csv is just multiple rows with 1 column, for example below:
row_1
row_2
row_3
The curl command works perfectly fine, I am trying to get python alternative for it, I tried below:
files = {'file': ('test.csv', open("some/path/to/test.csv", 'rb'), 'multipart/form-data')}
auth_token="<api token here>"
url="https://" + ip_address +"/eds/api/table/" + table_name + "/changes/addBulk?hasHeader=false"
headers = {
'Csrf-Token': 'nocheck',
'AuthToken': auth_token
}
response = requests.post(url, headers=headers, files=files, verify=False)
Any help is appreciated
I noticed in your curl url you have "eds" before "/api/..." but in your python version you do not.
curl_url = "https://<ip_address>/eds/api/table/table_name/changes/addBulk?hasHeader=false"
python_url = "https://" + ip_address +"/api/table/" + table_name + "/changes/addBulk?hasHeader=false"
Also, in python 3 it is cleaner to use an f-string like this:
url = f"https://{ip_address}**/eds/**api/table/{table_name}/changes/addBulk?hasHeader=false"
Everything else looks right to me. In the future it may help to set a break point on the response to see if there is any additional information with the 400 http response.
EDIT:
Okay then, can you try modifying your header to be:
headers = {
'Csrf-Token': 'nocheck',
'AuthToken': auth_token,
'Content-Type': 'multipart/form-data'
}
Also edit your files to be:
files = {
'data': ('test.csv', open("some/path/to/test.csv", 'rb'), 'multipart/form-data')
}
Final code should be:
auth_token = "<api token here>"
files = {
'data': ('test.csv', open("some/path/to/test.csv", 'rb'), 'multipart/form-data')
}
url = f"https://{ip_address}/eds/api/table/{table_name}/changes/addBulk?hasHeader=false"
headers = {
'Csrf-Token': 'nocheck',
'AuthToken': auth_token
}
response = requests.post(url, headers=headers, files=files, verify=False)
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=
I am trying to execute a curl GET request with python3
the request is:
curl -k -X GET -H "X-Some-Token: s.ggt5gvf344f"https://ip.address:port/v1/path/path
how it can be implemented?
import requests
url = "https://ip.address:port/v1/path/path"
payload={}
headers = {
'X-Some-Token': 's.ggt5gvf344f'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
or you can try http.client library which is much faster than requests
import http.client
conn = http.client.HTTPSConnection("ip.address", port)
payload = ''
headers = {
'X-Some-Token': 's.ggt5gvf344f'
}
conn.request("GET", "/v1/path/path", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
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}
I am trying to hit an endpoint with the raw request (CURL) as stated below :
!curl -i -X 'POST' "END_POINT" \
--form "api_key=xxxxx" \
--form "image= LOCAL_PATH_TO_IMAGE"
I tried using requests library of Python but I do not know how to construct the JSON request for the above.
def fetch_details(API_KEY, IMAGE_PATH, SERVICE_URL):
form = {
"api_key": API_KEY ,
"image": open(IMAGE_PATH,'rb')
}
header = {'content-type': 'application/json'}
url = SERVICE_URL
#response = requests.post(url, json = json.dumps(form), headers=header)
response = requests.post(url, json = json.dumps(json.loads(jsonpickle.encode(form))), headers=header)
if response.status_code != 200:
print('There is an error and the error is : ', response.text)
else:
attributes = response.json()
print(attributes)
I expect a JSON response for the above request but the output is "There is an error and the error : Server Error (500)"
The --form "image" parameter should contain the binary representation of the image.
The following curl command works as intended. Uses POST to send a bit of information to a web site.
curl 'https://...' \
-X PUT \
-d "submission[posted_grade]=65" \
-H "Authorization: Bearer 10~X"
What should be the equivalent python3 code, gives an Error 500: Internal Server Error
url_string = 'https://...'
data = "submission[posted_grade]=40"
data = data.encode('utf-8')
req = urllib.request.Request(url_string, data)
req.add_header("Authorization", "Bearer 10~X")
req.add_header("Content-Type", "application/json")
response = urllib.request.urlopen(req)
print(response.read())
Already tried
data = {'submission[posted_grade]': '40'}
data = json.dumps(data)
data = data.encode('utf-8')
Which gives "HTTP Error 422: Unprocessable Entity"
Any ideas on fixing it?
Thanks #cody
Lesson learned, PUT != POST
The following code works as expected:
url_string = 'https://...'
data = "submission[posted_grade]=40"
data = data.encode('utf-8')
req = urllib.request.Request(url=url_string, data=data, method='PUT')
req.add_header("Authorization", "Bearer 10~X")
response = urllib.request.urlopen(req)