I am struggling with this code as I have never encountered
Here is the Example code that click send provides.
curl --include \
--header "Authorization: Basic YXBpLXVzZXJuYW1lOmFwaS1wYXNzd29yZA==" \
--request POST \
--header "Content-Type: application/x-www-form-urlencoded" \
--data-binary "username=myusername&key=1234-I3U2RN34IU-43UNG&to=61411111111,64122222222,61433333333&senderid=example&message=testing" \
'https://api-mapper.clicksend.com/http/v2/send.php'
URL: https://developers.clicksend.com/docs/http/v2/#send-an-sms
Here is what I have figured out so far:
$BaseURL = "https://api-mapper.clicksend.com/http/v2/send.php"
$Header = #{
"Authorization" = "Basic"+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$APIKey"))
}
$body = #{
"useranme"="$Username"
"key"="$APIKey"
"to"="$To"
"senderid"="$from"
"message"=$Message
}
$Return = Invoke-RestMethod -Method Post -Headers $Header -ContentType "application/x-www-form-urlencoded" -Uri $BaseURL -Body $body
$return.InnerXml
I'm stuck on the --data-binary part of the code.
I believe using the --data-binary in curl is like creating a string in the body of the request:
$BaseURL = "https://api-mapper.clicksend.com/http/v2/send.php"
$Username = "Username"
$APIKey = "SomeAPIKey"
$To = "Recipient"
$From = "Sender"
$Message = "MessageFoRecipient"
$Header = #{
"Authorization" = "Basic"+ " " + ([System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$APIKey")))
}
$body = "username=$Username" + "&" + "key=$APIKey" + "&" + "to=$To" + "&" + "senderid=$From" + "&" + "message=$Message"
$return = Invoke-RestMethod -Method Post -Headers $Header -ContentType "application/x-www-form-urlencoded" -Uri $BaseURL -Body $body
$return.InnerXml
Invoke-RestMethod assumes that you want your POST body to be application/x-www-form-urlencoded (unless otherwise specified, e.g. XML, JSON). You must be having an issue with something such as the fact that the Authorization header doesn't have a space between Basic and the Base64 string, or the fact that username has a typo.
$BaseURL = 'http://localhost:8000'
$Username = 'api-username'
$ApiKey = 'api-password'
$To = '61411111111,64122222222,61433333333'
$From = 'example'
$Message = 'testing'
$SenderId = 'example'
$Body = #{
username = $Username
key = $ApiKey
to = $To
senderid = $SenderId
message = $Message
}
$Header = #{
Authorization = 'Basic ' + ([System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$APIKey")))
}
$Return = Invoke-RestMethod -Method Post -Headers $Header -Uri $BaseURL -Body $Body
$Return.InnerXml
Yields the following HTTP request:
POST / HTTP/1.1
Host: localhost:8000
Authorization: Basic YXBpLXBhc3N3b3Jk
User-Agent: Mozilla/5.0 (Windows NT 10.0; Microsoft Windows 10.0.19042; en-US) PowerShell/7.2.1
Content-Length: 112
Content-Type: application/x-www-form-urlencoded
key=api-password&message=testing&username=api-username&to=61411111111%2C64122222222%2C61433333333&sender=example
Related
I have been challenged to get a response from an api with powershell.
I have little to no experience with powershell, but have at least been able to get a response from the API provider, but not a response i can use, so i hope someone can help me.
The photo is of the documentaion i have
Documentation
What i can't figure out is how i send the message that i want a response for.
The command is the specific api that i need to use, and it has some inputs as seen in the photo.
Input to API:
StreetName
BuildingIdentifier
Floor
Suite
DistrictCode
This is what i got so far.
$uri = 'SomeUrl.com'
$command = '/Ois/RealUnit/Address'
$token = 'SomeSecureToken'
$contentType = 'application/json'
$secureToken = ConvertTo-SecureString $token -AsPlainText -force
$webResult = Invoke-RestMethod -Method get -Uri $uri -ContentType $contentType -Token $secureToken
write-output $webResult
What i know but i don't know how to use or i it has to be used is as follows.
Request URL: https://SomeUrl.com/Ois/RealUnit/Address
Response body: is JSON and i only need the response for "unitUse"
Response Code: I also know that a good response gives the code 200
Curl: I also know that something called CURL looks a bit like this curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' -d 'StreetName=STREET&BuildingIdentifier=123&Floor=12&Suite=th&DistrictCode=1234' 'https://SomeUrl.com/Ois/RealUnit/Address'
Reponse Header: Looks like this
{ "access-control-allow-headers": "Content-Type", "access-control-allow-methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "access-control-allow-origin": "*", "cache-control": "private", "content-length": "7604", "content-type": "application/json; charset=utf-8", "date": "Tue, 08 Mar 2022 13:21:27 GMT", "server": "Microsoft-IIS/8.5", "strict-transport-security": "max-age=31536000", "vary": "Accept", "x-aspnet-version": "4.0.30319", "x-powered-by": "ServiceStack/5.10 NET45 Win32NT/.NET, ASP.NET" }
$uri = 'https://SomeUrl.com/Ois/RealUnit/Address'
$token = 'SomeSecureToken'
$contentType = 'application/json'
$secureToken = ConvertTo-SecureString $token -AsPlainText -force
$Body = #{
StreetName = "STREET"
BuildingIdentifier = 123
Floor = 12
Suite = "th"
DistrictCode = 1234
}
$webResult = Invoke-RestMethod -Method POST -Uri $uri -ContentType $contentType -Token $secureToken -Body $Body
write-output $webResult
I can't really remember if you have to convert body to JSON data or if the 'Invoke-RestMethod' does it automatically. In any case: this is how you could do it:
$webResult = Invoke-RestMethod -Method POST -Uri $uri -ContentType $contentType -Token $secureToken -Body ($Body | ConvertTo-Json)
Am Currently trying to query the authToken
$uri = 'http://xxx.centreon/api/index.php?action=authenticate'
$headers = #{
'username' = 'exemple'
'password' = 'exemple'
}
Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -ContentType application/x-www-form-urlencoded
But am having bad parameters
Via linux : curl -s -d "username=exemple&password=exemple" -H "Content-Type: application/x-www-form-urlencoded" -X POST http://xxx.centreon/api/index.php?action=authenticate
{"authToken":"NWU5OWM0YjRhMjIzMDYuMzg2NzYyMDY="}-
So this is a vague question but i do see how things might be wrong.
First the Username and Password are usually in the Body not the Header.
In your curl command I see its being passed as -d which would be the Body
$uri = 'http://xxx.centreon/api/index.php?action=authenticate'
$Body = #{
'username' = 'exemple'
'password' = 'exemple'
}
Invoke-RestMethod -Uri $uri -Method Post -body $Body -ContentType "application/x-www-form-urlencoded"
How do i convert this curl command to powershell? This works perfectly using curl however in powershell i am geting 401 unauthorized.
I have tried everything i can think of. This code can only be executed inside a certain environment. i am trying to pass a cookie i know is valid into the header of the second. The first request works well, the second request which is meant the return json does not. Instead returns 401
The command requires cookies to authenitcate
curl.exe -vu SuperGabriel:SuperGabriel#2019 -X POST -H "X-Application: 3rdParty" https://webadmin.td90.centile-dev.com/restletrouter/v1/service/Login --insecure
curl.exe -v -H "Cookie: thirdParty_SESSIONID=6483556424564819468" -H "X-
Application: 3rdParty" https://webadmin.td90.centile-dev.com/restletrouter/v1/3rdParty/AdmtiveDomain --insecure
curl.exe -v -H "Cookie: thirdParty_SESSIONID=1312545750448673312" -H "X-Application: 3rdParty" https://webadmin.td90.centile-dev.com/restletrouter/v1/3rdParty/CallRecord/0.106.?day=20190301 -k --insecure -o
"C:\Users\stephenm\Documents\test.csv"
Here is my powershell code so far.
add-type #"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"#
[System.Net.ServicePointManager]::CertificatePolicy = New-Object
TrustAllCertsPolicy
$user = "SuperGabriel"
$pass = "SuperGabriel#2019"
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$headers = #{
"Authorization" = $basicAuthValue
"X-Application" = "3rdParty"
}
$login = Invoke-WebRequest -Uri https://webadmin.td90.centile-dev.com/restletrouter/v1/service/Login -Headers $headers -Method Post
$headers = #{
"Authorization" = $basicAuthValue
"X-Application" = "3rdParty"
"Cookie" ="thirdParty_SESSIONID=4436753218874838616"
"Content-Type" = "application/json"
}
try
{
$admtiveDomains = Invoke-WebRequest -Uri https://webadmin.td90.centile-
dev.com/restletrouter/v1/3rdParty/AdmtiveDomain -Headers $headers -Method
Get
}catch{
echo $ErrorMessage = $_.Exception.Message
}
many thanks
Is it possible you need to get a token first that you then need to convert to a base64 string?
$uri = 'https://webadmin.td90.centile-dev.com/restletrouter/v1/service/Login'
$body = #{ username = 'SuperGabriel'; password = 'SuperGabriel#2019' }
$bodyjson = $body | convertTo-Json
$ctype = "application/json"
$token = invoke-restmethod -uri $uri -method POST -body $bodyjson -contenttype $ctype
I don't know what object $token would return, but you would essentially then convert the returned string and continue on from there.
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($token))
I'm trying to upload a text file in our Salesforce application using PowerShell.
The curl code which I'm trying to mimic in PowerShell is:
curl -X POST -H "Authorization: {SESSION_ID}" \
-H "Content-Type: multipart/form-data" \
-F file=#document.txt \
-F "name__v=myDocument" \
-F "type__v=Undefined" \
-F "lifecycle__v=Unclassified" \
https://{server}/api/{version}/objects/documents
Here is the PowerShell code which I have written taking hint from the web:
$URL="https://{server}/api/{version}/auth"
$CT="application/x-www-form-urlencoded"
$User="user"
$Password="pass"
$SessionID=(Invoke-RestMethod -Method Post -Uri $URL -Body #{"Content-Type" = $CT; "username" = $User; "password" = $Password}).sessionId
$URL="https://{server}/api/{version}/objects/documents"
$boundary=[System.Guid]::NewGuid().ToString()
$LF="`r`n"
$File=Get-Content("....\test.txt")
$fileBin=[System.IO.File]::ReadAllBytes("....\test.txt")
$enc=[System.Text.Encoding]::GetEncoding("iso-8859-1")
$fileEnc=$enc.GetString($fileBin)
$Body1=(
"--$boundary",
"Content-Disposition: form-data; name__v=`"kaz.txt`"; type__v=`"Undefined`"; lifecycle__v=`"Unclassified`"",
"Content-Type: application/octet-stream$LF",
$fileEnc,
"--$boundary--$LF"
) -join $LF
$Body2 = (
"file=$File; name__v=`"kaz.txt`"; type__v=`"Undefined`"; lifecycle__v=`"Unclassified`""
)
Invoke-RestMethod -Method POST -Uri $URL -Headers #{"Authorization" = $SessionID; "Content-Type" = "multipart/form-data; boundary=`"$boundary`""} -Body $Body1
Invoke-RestMethod -Method POST -Uri $URL -Headers #{"Authorization" = $SessionID; "Content-Type" = "multipart/form-data; boundary=`"$boundary`""} -Body $Body2
None of these are working and I'm getting error
PARAMETER_REQUIRED lifecycle__v: Missing required parameter : lifecycle__v.
I modified the body and now its working fine
$Body = (
"--$boundary", "Content-Disposition: form-data; name=`"file`"; filename=`"test.docx`"", "Content-Type: application/octet-stream$LF", $fileEnc,
"--$boundary", "Content-Disposition: form-data; name=`"lifecycle__v`"", "", "Unclassified",
"--$boundary", "Content-Disposition: form-data; name=`"type__v`"", "", "Undefined",
"--$boundary--"
)-join $LF
Invoke-RestMethod -Method POST -Uri $URL -Headers #{"Authorization" = $SessionID; "Content-Type" = "multipart/form-data; boundary=$boundary"} -Body $Body
I'm trying to use the Invoke-RestMethod cmdlet in PowerShell 3 and 4, to upload a large binary file using a REST API's multipart/form-data upload. Here is a working cURL example on how to perform what I want to do in PowerShell:
curl -i -k -H "accept: application/json" -H "content-type: multipart/form-data" -H "accept-language: en-us" -H "auth: tokenid" -F file="#Z:\large_binary_file.bin" -X POST "https://server/rest/uri2"
I would love to see a working example on how to use Invoke-RestMethod to POST a multipart/form-data. I found a blog post from the PowerShell team showing how to use Invoke-RestMethod to upload to OneDrive (aka SkyDrive), but doesn't work well. I'd also like to avoid using System.Net.WebClient if at all possible. I also found another thread here on Stackoverflow, but it really didn't help much.
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
$server = "https://server"
uri = "/rest/uri1"
$headers = #{"accept" = "application/json"; "content-type" = "application/json";"accept-language" = "en-us"}
$body = #{"userName" = "administrator"; "password" = "password"}
$method = "POST"
#Get Session ID
$resp = Invoke-RestMethod -Method $method -Headers $headers -Uri ($server+$uri) -body (convertto-json $Body -depth 99)
$sessionID = $resp.sessionID
#Upload file
$uri = "/rest/uri2"
$headers = #{"accept" = "application/json";"content-type" = "multipart/form-data"; "accept- language" = "en-us"; "auth" = $sessionID}
$medthod = "POST"
$largeFile = "Z:\large_binary_file.bin"
I have tried both ways of using Invoke-RestMethod:
Invoke-RestMethod -Method $method -Headers $headers -Uri ($server+$uri) -InFile $largeFile
or
$body = "file=$(get-content $updateFile -Enc Byte -raw)"
Invoke-RestMethod -Method $method -Headers $headers -Uri ($server+$uri) -body $body
I notice couple of mistakes in your invoke statement. First, you need to use POST keyword instead of string value. Second, make sure that Content-Type is set to multipart/form-data. So this is my revised statement -
$uri = "http://blahblah.com"
$imagePath = "c:/justarandompic.jpg"
$upload= Invoke-RestMethod -Uri $uri -Method Post -InFile $imagePath -ContentType 'multipart/form-data'
You can check the response from the server by checking $upload.