VB.NET Rest Client POST -d body - vb.net

I have a Rest API that i can query normal. Unfortunately I have to submit parameter values as body content.
CURL code is like
curl -X POST "https://URL" -H "accept: application/json" -H "authorization: bearer [BEARER GOES HERE] -H "Content-Type: application/json" -d "{ \"ids\": [\"ldt:b3b6ea07a6b848fdb5ca3e36bf1e3678:21475014799\",\"ldt:b3b6ea07a6b848fdb5ca3e36bf1e3678:8590616500\"]}"
I'm able to query the API like this:
Dim request = New RestRequest("/detects/queries/detects/v1, Method.POST)
request.AddHeader("Accept", "application/json")
request.AddHeader("Authorization", "bearer " + bearer)
data_response = data_client.Execute(request)
data_response_raw = data_response.Content
The thing that I'm struggling with is to add the body / -d part of the curl request. The content is fairly simple:
{"ids":["ldt:b3b6ea07a6b848fdb5ca3e36bf1e3678:21475014799"]}
I tried request.AddBody(Of RequestBody)(body) but that gives me only a syntax error.
Can anybody give me a hint on this?
Thank you!

I have personally never used RestSharp, however here is the documentation related to specifying the request body of the RestRequest object: https://restsharp.dev/usage/parameters.html#request-body
Specifically, the documentation suggests using the AddJsonBody method: https://restsharp.dev/usage/parameters.html#addjsonbody
Here is an example using your desired body content:
Dim param = New With {Key .ids = {"ldt:b3b6ea07a6b848fdb5ca3e36bf1e3678:21475014799"}}
request.AddJsonBody(param)

Davids hint did the trick - this is the code working
Dim sb0 As New StringBuilder
sb0.Append(Chr(123) + Chr(34) + "ids" + Chr(34) + Chr(58) + Chr(91))
Dim append As String
Dim zahl = 0
Do Until zahl = nmbr2 - 1
append = raw_d("resources")(zahl)
sb0.Append(Chr(34) + append + Chr(34) + ",")
zahl = zahl + 1
Loop
append = raw_d("resources")(zahl)
sb0.Append(Chr(34) + append + Chr(34))
sb0.Append(Chr(93) + Chr(125))
Dim body As String = sb0.ToString
Dim request = New RestRequest("xxx", Method.POST)
request.AddHeader("Accept", "application/json")
request.AddHeader("Authorization", "bearer " + bearer)
request.AddJsonBody(body)
data_response = data_client.Execute(request)
data_response_raw = data_response.Content
Maybe not the prettiest way to create the body but it works ;)

Related

Curl URL into vb.net

Hi i'm trying to find a solution how to implement the below curl in vb.net:
curl -X 'GET' \ 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_market_cap=false&include_24hr_vol=false&include_24hr_change=false&include_last_updated_at=false&precision=full' \ -H 'accept: application/json'
Using System.Net.Http you can do that as follows:
Private Sub GetBtcPrice()
Using client As System.Net.Http.HttpClient = New System.Net.Http.HttpClient
client.DefaultRequestHeaders.Add("accept", "application/json")
Dim sb As New StringBuilder
sb.Append("?")
sb.Append("ids=bitcoin&")
sb.Append("vs_currencies=usd&")
sb.Append("include_market_cap=false&")
sb.Append("include_24hr_vol=false&")
sb.Append("include_24hr_change=false&")
sb.Append("include_last_updated_at=false&")
sb.Append("precision=full")
Dim response As HttpResponseMessage = client.GetAsync("https://api.coingecko.com/api/v3/simple/price" & sb.ToString).GetAwaiter().GetResult()
Dim sResponse As String = response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
Console.WriteLine("response: " & sResponse)
End Using
End Sub
Dim webClient As New System.Net.WebClient
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim result As String = webClient.DownloadString("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_market_cap=false&include_24hr_vol=false&include_24hr_change=false&include_last_updated_at=false&precision=full")
And its stored in variable result as json

Unable to create a cURL string in VB.net

I I'm trying to integrate an SMS service in my desktop application in VB.net but I'm not able to create the correct string to to that.
This is the autentication method:
Session Key example
curl -XGET 'https://app.esendex.it/API/v1.0/REST/login' -H 'Content-Type: application/json'
-H 'Authorization: Basic base64_encode(MY_USERNAME:MY_PASSWORD)'
On success, the above command returns the following response: USER_KEY;SESSION_KEY
This is what I've done:
Private Sub SMS()
Dim username = "myuser"
Dim password = "mypass"
Dim encoded As String
encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password))
Dim webRequest As WebRequest = WebRequest.Create("https://app.esendex.it/API/v1.0/REST/login")
webRequest.ContentType = "application/json"
webRequest.Headers.Add("Authorization", "Basic " + encoded)
webRequest.Method = "GET"
Dim myHttpWebResponse = CType(webRequest.GetResponse(), HttpWebResponse)
TextBox1.Text = myHttpWebResponse.ToString
End Sub
but myHttpWebResponse.ToString doesn't get USER_KEY & SESSION_KEY
Can someone help me ?

Correct way to add "autorization : bearer" header in an HttpWebRequest

Context
I want to code this curl command in VB.NET
curl -X GET 'https://api.twitch.tv/helix/users?login=crunchprank' \
-H 'Authorization: Bearer YY' \
-H 'Client-Id: XX'
This curl works perfectly if executed in online curl like https://reqbin.com/curl
Client Id and Bearer are ok.
Here is my VB.Net code
Dim strTwitchApiRequestChannelUrl As String
Dim httpTwitchApiRequestChannel As HttpWebRequest
Dim httpTwitchApiRequestChannelResponse As HttpWebResponse
Dim strTwitchApiRequestChannelResponse As String
strTwitchApiRequestChannelUrl = "https://api.twitch.tv/helix/users?" & strTwitchChannelId
httpTwitchApiRequestChannel = CType(WebRequest.Create(strTwitchApiRequestChannelUrl), HttpWebRequest)
httpTwitchApiRequestChannel.Timeout = 10000
httpTwitchApiRequestChannel.Headers("client_id") = "XX"
httpTwitchApiRequestChannel.Headers("Authorization") = " Bearer " & YY
httpTwitchApiRequestChannelResponse = TryCast(httpTwitchApiRequestChannel.GetResponse(), HttpWebResponse)
If httpTwitchApiRequestChannelResponse.StatusCode = 200 Then
Using responseStream As Stream = httpTwitchApiRequestChannelResponse.GetResponseStream()
Dim reader As StreamReader = New StreamReader(responseStream)
strTwitchApiRequestChannelResponse = reader.ReadToEnd()
End Using
End If
Issue:
I get an 401 response code. I'm pretty sure it's because of the autorization headers. It missed the :
Same issue if i did this :
httpTwitchApiRequestChannel.Headers("Authorization") = ": Bearer " & YY
And I cannot do this httpTwitchApiRequestChannel.Headers("Authorization: Bearer ") = YY because i got an error: Specified value has invalid HTTP Header characters. (Parameter 'name')"}

convert CURL request into VBA xml Object in MS-Access

I am trying to handle moodle data from our schools MS-Access database using VBA-code to post xml.objects.
I implemented the following code from an example for using the RESTful-API into my VBA-code (source https://moodle.org/plugins/webservice_restful):
json code:
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H 'Authorization: {token}' \
-d'{"options": {"ids":[6]}}' \
"https://localhost/webservice/restful/server.php/core_course_get_courses"
This is my conversion in VBA in a ms-access db module so far:
Option Compare Database
Option Explicit
Private Sub btnTestMoodleApi_Click()
Dim objRequest As Object
Dim strResult As String
Dim strPostData As String
Dim strToken as String
Dim strURL as String
strToken = xxx
strURL = xxx
Set objRequest = CreateObject("MSXML2.XMLHTTP")
strPostData = "'options[ids][0]=8'"
With objRequest
.Open "POST", strURL & "/webservice/restful/server.php/core_course_get_courses"
.setRequestHeader "Authorization", strToken
' .setRequestHeader Chr(34) & "Authorization" & Chr(34), Chr(34) & EncodeBase64(strToken) & Chr(34) ' is any of this necessary? I also tried single quotes chr(39)
.setRequestHeader "Content-Type", " application/x-www-form-urlencoded"
.setRequestHeader "Accept", "application/json"
.Send (strPostData)
While .ReadyState <> 4
DoEvents
Wend
strResult = .responseText
Debug.Print strResult
End With
End Sub
I am not sure if the following function that I found is necessary:
Function EncodeBase64(text As String) As String
Dim arrData() As Byte
arrData = StrConv(text, vbFromUnicode)
Dim objXML As MSXML2.DOMDocument60
Dim objNode As MSXML2.IXMLDOMElement
Set objXML = New MSXML2.DOMDocument60
Set objNode = objXML.createElement("b64")
objNode.DataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = objNode.text
Set objNode = Nothing
Set objXML = Nothing
End Function
Either way the return is an error that there was no authorization header in the request {"exception":"moodle_exception","errorcode":"noauthheader","message":"No Authorization header found in request sent to Moodle"}. I guessed it is a formatting problem, so I tried various sorts of quotes around what I guess is the header type declaration ("Authorization") and the token, nothing worked. Also I found this remark by another person under the CURL source:
"The authorization header was stripped by my version of Apache 2, resulting in a noauthheader error. It worked when added this directive:
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1"
However I would not know if that error source applies to my case and how I would implement the directive in my VBA code. Any help would be very much appreciated! By the way this is the corresponding php code in a locallib.php file where I believe the curl request to be directed to:
* Get the webservice authorization token from the request.
* Throws error and notifies caller on failure.
*
* #param array $headers The extracted HTTP headers.
* #return string $wstoken The extracted webservice authorization token.
*/
private function get_wstoken($headers) {
$wstoken = '';
if (isset($headers['HTTP_AUTHORIZATION'])) {
$wstoken = $headers['HTTP_AUTHORIZATION'];
} else {
// Raise an error if auth header not supplied.
$ex = new \moodle_exception('noauthheader', 'webservice_restful', '');
$this->send_error($ex, 401);
}
return $wstoken;
}

How to POST using -x in VBA HTTP API

I have a bunch of API calls to STRIPE which are working well.
Generally I use the cURL version and work out what I need to do.
I have just come across the need to DELETE a subscription:
curl https://api.stripe.com/v1/subscriptions/sub_FpZkRarex4obNX \
-u sk_test_VHkTM0bOtpsE1dBnTxFbMBAk00WnBQnyI5: \
-X DELETE
The issue is I have no idea how to use the -x in VBA
My current code for other calls is:
api_Key = getStripeAPI
req = "DELETE"
Set httpReq = CreateObject("MSXML2.ServerXMLHTTP")
httpReq.Open "POST", "https://api.stripe.com/v1/subscriptions/" & stripeSubID, False
httpReq.setRequestHeader "Authorization", "Bearer " & api_Key
httpReq.send req
strResponse = httpReq.responseText
Debug.Print strResponse
writeToText strResponse
Set parsed = JsonConverter.ParseJson(strResponse)
I know the above code is incorrect but if someone can let me know how to utilise -X that would be great.
You're already using it, just passing the wrong argument. It's the first argument to .Open:
httpReq.Open "DELETE", "https://api.stripe.com/v1/subscriptions/" & stripeSubID, False
ok wow i just figured it by myself.. after 45 mins of trying.
For those looking fr this:
-x DELETE means use DELETE as the "GET"/"POST" option.
working code:
api_Key = getStripeAPI
Set httpReq = CreateObject("MSXML2.ServerXMLHTTP")
httpReq.Open "DELETE", "https://api.stripe.com/v1/subscriptions/" & stripeSubID, False
httpReq.setRequestHeader "Authorization", "Bearer " & api_Key
httpReq.send
strResponse = httpReq.responseText
Debug.Print strResponse
writeToText strResponse
Set parsed = JsonConverter.ParseJson(strResponse)