Is it possible to convert a cURL request to a VBA winHttpRequest? - excel

I have the request below, trying to get a paypal auth token to retrieve a transaction list from my account.
curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "client_id:secret" \
-d "grant_type=client_credentials"
And I have gone this far:
Set objHTTP = New WinHttp.WinHttpRequest
sURL = "https://api.sandbox.paypal.com/v1/oauth2/token"
objHTTP.Open "POST", sURL, False
'what should go here? is the POST request correct? Are -H in cURL for headers?
objHTTP.send (sBody)
Can you help me get this working? Is there maybe an easier way to have the cURL requests "converted"?
EDIT:
sURL = "https://api.sandbox.paypal.com/v1/oauth2/token"
objHTTP.Open "POST", sURL, False
objHTTP.SetRequestHeader "Content-Type", "application/json"
objHTTP.SetRequestHeader "Accept", "application/json"
User = "user"
Password = "password"
objHTTP.SetRequestHeader "Authorization", "Basic " & Base64Encode(User + ":" + Password)
Runtime Error 5
Invalid procedure call or arguement. Any ideas?

Here's a working example. I don't run Excel anymore so I can't get at the code but it's in there, just open the macro editor. This uses the MSXML library to do an XHR fetch from a REST API.
https://rack.pub/cdn/miles.xlam

Related

Error throwing when connecting api with client I'd and key

I'm trying to access data through an API that takes in a X-client-id and x-api-key. I've tried the following so far but it's not working. Can anyone help?
Dim request as new winhttprequest
Request.open "Get", url, False
Request.setrequestheader "Accept", "application/json"
Request.setrequestheader "X-client-id", "[Id]"
Request.setrequestheader "x-api-key", "[key]"

Python call rest api to get data from url

I've created a Bash script to get the data from the url using rest API from a appliance using username, password and saving the Session ID into a Variable and then using the session ID to get the data into csv format which is working fine.
I want to change the bash code into python3 code as i'm parsing it using pandas.
Bash Code:
#!/bin/bash
sessionID=$(curl -k -H "accept: application/json" -H "content-type: application/json" -H "x-api-version: 120" -d '{"userName":"administrator","password":"adminpass"}' -X POST https://hpe.sysnergy.com/rest/login-sessions | jq -r ".sessionID")
curl -k -H 'accept: application/json' \
-H 'content-type: text/csv' \
-H 'x-api-version: 2' \
-H "auth: $sessionID" \
-X GET https://hpe.sysnergy.com/rest/resource-alerts
Python Version of tries code:
#!/usr/bin/python3
import requests
import json
url = "https://hpe.sysnergy.com/rest/login-sessions"
data = {'username': 'administrator', 'password': 'adminpass'}
headers = {'Content-type': 'text/csv', 'Accept': 'application/json', 'x-api-version': 2}
r = requests.post(url, data=json.dumps(data), headers=headers)
print(r)
I am getting below error:
Error:
requests.exceptions.InvalidHeader: Value for header {x-api-version: 2} must be of type str or bytes, not <class 'int'>
if i convert int to str as '2' then it gives another ssl error:
requests.exceptions.SSLError: HTTPSConnectionPool(host='hpe.synerg.com', port=443): Max retries exceeded with url: /rest/login-sessions (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:877)'),))
EDIT:
I have tried little different approach to get the same code format as bash in python but now it returns new error with new response code.
import os
import requests
sessionID = os.getenv('sessionID')
headers = {
'accept': 'application/json',
'content-type': 'text/csv',
'x-api-version': '2',
'auth': f"{sessionID}",
}
data = '{"userName":"administrator","password":"adminpassword"}'
response = requests.post('https://hpe.synergy.com/rest/login-sessions', headers=headers, data=data, verify=False)
print(response)
Error:
/python3/lib64/python3.6/site-packages/urllib3/connectionpool.py:1020: InsecureRequestWarning: Unverified HTTPS request is being made to host 'hpe.synergy.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning,
<Response [415]>
Please help or suggest the way to achieve same function in the python.
You first need to make a POST request to get the sessionID, then you need to make a GET request. Also note the headers are slightly different for the 2 requests. Something like this should work:
import requests
session = requests.Session()
url = "https://hpe.sysnergy.com/rest/login-sessions"
credentials = {"userName": "administrator", "password": "adminpass"}
headers = {"accept": "application/json",
"content-type": "application/json",
"x-api-version": "120",
}
response = session.post(url, headers=headers, json=credentials, verify=False)
session_id = response.json()["sessionID"]
url = "https://hpe.sysnergy.com/rest/resource-alerts"
headers = {"accept": "application/json",
"content-type": "text/csv",
"x-api-version": "2",
"auth": session_id,
}
response = session.get(url, headers=headers, verify=False)
print(response)
#print(response.content) # returns bytes
#print(response.text) # returns string

Configure correctly CORS with wai-cors

I am struggling with Servant and the CORS configuration: I am exposing and API through Servant and I have the following configuration:
-- Wai application initialization logic
initializeApplication :: IO Application
initializeApplication = do
let frontCors = simpleCorsResourcePolicy { corsOrigins = Just ([pack "https://xxxx.cloudfront.net"], True)
, corsMethods = ["OPTIONS", "GET", "PUT", "POST"]
, corsRequestHeaders = simpleHeaders }
return
$ cors (const $ Just $ frontCors)
$ serve (Proxy #API)
$ hoistServer (Proxy #API) toHandler server
When I perform a query like this through Chromium (by copying and pasting):
curl 'https://api.xxx/' \
-H 'Accept: application/json, text/plain, */*' \
-H 'Referer: https://xxx.cloudfront.net' \
-H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36' \
-H 'Authorization: Bearer XXX==' \
--compressed
It works but if I copy-paste the fetch query in the dev console:
fetch("https://api.xxx", {
"headers": {
"accept": "application/json, text/plain, */*",
"authorization": "Bearer XXX=="
},
"referrer": "https://xxx.cloudfront.net/",
"referrerPolicy": "no-referrer-when-downgrade",
"body": null,
"method": "GET",
"mode": "cors",
"credentials": "include"
});
I get:
> Access to fetch at 'https://api.xxx' from origin 'https://xxx.cloudfront.net' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
polyfills-es2015.3eb4283ca820c86b1337.js:1 GET https://api.xxx net::ERR_FAILED
e.fetch # polyfills-es2015.3eb4283ca820c86b1337.js:1
> (anonymous) # VM20:1
> x:1 Uncaught (in promise) TypeError: Failed to fetch
Any hints regarding that? Especially why it works in cUrl and not in Chromium?
Thanks in advance.
It was a basic CORS issue, in fact, sending Authorization without having it in the corsRequestHeaders makes the request rejected.
I should have written:
, corsRequestHeaders = ["Authorization", "Content-Type"]

MSXML2.XMLHTTP not working in company network

I've built a macro for a client that POSTs some data to an external URL which requires basic authentication (get/save data in cloud database via api). When I'm running the macro from home (or basically anywhere) it works perfectly. However, when my client runs it (while in his company network), he gets a timeout error message after a few seconds. Any suggestions on what the cause could be?
Here is my code:
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
With objHTTP
.Open "POST", url, False
.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
.SetRequestHeader "Content-Type", "application/json"
.SetRequestHeader "Accept", "application/json"
.SetRequestHeader "Authorization", "Basic " + Base64EncodeString(apiKey + ":" + apiPw)
.Send (data)
End With

I am looking to convert this cURL command into NodeJS

I am working with Spiceworks, a multipurpose IT tool and am trying to create a script to update our product keys in the database. I am not very experience with NodeJS so I am pretty confused how to create the equivalent to this curl command:
curl
'https://spiceworks.elogicgroup.com/software_licenses.js?device_view=true'
\
-H 'Cookie: spiceworks_session=BAh7F...9ffe' \
-H 'Origin: https://spiceworks.elogicgroup.com' \
-H 'Content-Type: multipart/form-data; boundary=----BOUNDARY' \
-H 'Cache-Control: max-age=0' \
--data-binary $'------BOUNDARY\r\nContent-Disposition:
form-data;name="authenticity_token"\r\n\r\ blfbEi...cK+/k=
\r\n------BOUNDARY\r\nContent-Disposition: form-data;
name="_pickaxe"\r\n\r\n\u2e15\r\n------BOUNDARY\r\nContent-Disposition:
form-data; name="software_license[software_id]"\r\n\r\n
513\r\n------BOUNDARY\r\nContent-Disposition: form-data; name="software_installation"\r\n\r\n
3854\r\n------BOUNDARY\r\nContent-Disposition: form-data; name="software_license[type]"\r\n\r\nIndividualLicense\r\n------BOUNDARY\r\nContent-Disposition:
form-data; name="software_license[key]"\r\n\r\n
54321\r\n------BOUNDARY--\r\n'
BAh7F...9ffe is your SpiceWorks session cookie.
blfbEi...cK+/k is an authentication token.
513 is the ID of the software application
3854 ties the software application to a specific install on a specific computer
I would really appreciate any tips or directions you all could point me in, I am really struggling with this.
Thanks!!
Jack
Using https://github.com/mikeal/request
var r = request.post({
url: 'https://spiceworks.elogicgroup.com/software_licenses.js?device_view=true',
headers: {
'Cookie': 'spiceworks_session=BAh7F...9ffe',
'Origin': 'https://spiceworks.elogicgroup.com/',
'Cache-Control': 'max-age=0'
}
});
var form = r.form();
form.append('authenticity_token', 'blfbEi...cK+/k');
. . .

Resources