I have the following Json in the body of a Postman. what would be equivalent code in Powershell to send rest API via invoke-webrequest or via invoke-restmethod?
Postman Body:
{
"extra_vars": {
"servername": "apicall1234",
"servers": "server01,server02,server06,server-12345"
}
}
You can pass a request body via the -Body parameter on either of the web cmdlets. As with Postman (or any other HTTP client), you'll need to provide an address and a method/verb.
$uri = 'https://<url goes here>/path'
$reqBody = '{ "extra_vars": { "servername": "apicall1234", "servers": "server01,server02,server06,server-12345" } }'
Invoke-WebRequest -Uri $uri -Body $reqBody -Method Post
Related
I have the below curl command which i am trying to convert to powershell, but i am not sure on how to handle the multi header inputs and the JSON input
Any help is highly appreciated
curl --location --request POST 'https://anypoint.studio.com/cloudhub/api/v2/applications' \
--header 'X-ANYPNT-ENV-ID: 4a96abfd4f5237cf1b64' \
--header 'X-ANYPNT-ORG-ID: bc0d-3b9fd79234ad' \
--header 'Authorization: Bearer 3esede-a44b-29ab8841b508' \
--form 'file=#"/C:/Users/pgi/Downloads/eafdc-flow-proxy-v1.2.jar"' \
--form 'appInfoJson="{
\"domain\": \"testproxy-test\",
\"Version\": {
\"version\": \"4.4.0\"
},
\"properties\": {
\"platform.client_id\": \"8f95qw3sa4b679aaa699cf0f5c6b6\",
\"secure.key\": \"sYf%NJ7F^y&3lNRH*D$#\",
\"env\": \"dev\",
\"platform.client_secret\": \"acF0JHFUEFH8829a481D9c37EF364be7a\"
},
\"propertiesOptions\": {
\"secure.key\": {
\"secure\": true
},
\"anypoint.platform.client_secret\": {
\"secure\": true
}
},
\"region\": \"us-west-1\",
\"monitoringEnabled\": true,
\"monitoringAutoRestart\": true,
\"workers\": {
\"amount\": 1,
\"type\": {
\"name\": \"Micro\",
\"weight\": 0.1,
\"cpu\": \"0.1 vCores\",
\"memory\": \"500 MB memory\"
}
},
\"loggingNgEnabled\": true,
\"persistentQueues\": true
}"' \
--form 'autoStart="true"'
You can replace curl with Invoke-WebRequest and parse the JSON with ConvertFrom-Json.
$r = Invoke-WebRequest -Uri $uri -Method Post -Body $body
$j = ConvertFrom-Json $r.Content
I've left out setting the value of $uri and $body. I hope this is enough for you to get started with.
Update
First response was written too quickly. You probably need to pass header and body.
Like curl, Invoke-Webrequest is powerful and complex. You can find online documentation here:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7.2&WT.mc_id=ps-gethelp
You'll need to use the Headers and Body Parameters:
-Headers <System.Collections.IDictionary>
Specifies the headers of the web request. Enter a hash table or dictionary.
To set UserAgent headers, use the UserAgent parameter. You can't use this parameter to specify User-Agent or cookie headers.
Content related headers, such as Content-Type is overridden when a MultipartFormDataContent object is supplied for Body .
-Body <System.Object>
Specifies the body of the request. The body is the content of the request that follows the headers. You can also pipe a body value to Invoke-WebRequest.
The Body parameter can be used to specify a list of query parameters or specify the content of the response.
When the input is a GET request and the body is an IDictionary (typically, a hash table), the body is added to the URI as query
parameters. For other request types (such as
POST), the body is set as the value of the request body in the standard name=value format.
The Body parameter may also accept a System.Net.Http.MultipartFormDataContent object. This facilitates multipart/form-data requests. When a MultipartFormDataContent object is supplied for Body , any Content related headers supplied to the ContentType , Headers , or WebSession parameters is overridden by the Content headers of the MultipartFormDataContent object. This feature was added in PowerShell 6.0.0.
Looks like you'll have to create a MultipartFormDataContent object. Note this was added in PowerShell Version 6, so you can't use the Windows built-in default version 5. If you haven't already, you'll probably need to install the latest version of Version 7. (I use version 7 and it's great.)
So for headers you'd create something like:
$headers = [ordered]#{
'X-ANYPNT-ENV-ID' = '4a96abfd4f5237cf1b64'
'X-ANYPNT-ORG-ID' = 'bc0d-3b9fd79234ad'
'Authorization' = 'Bearer 3esede-a44b-29ab8841b508'
}
Then make a call like:
$r = Invoke-WebRequest -Uri $uri -Method Post `
-Headers $headers -Body $myMultipartFormDataContent
I haven't used MultipartFormDataContent so I'll leave that up to you. I hope this provides you with a good starting point.
I need to post json request to url with powershell.
The curl body looks like that:
{
"records":
[ {
\"source\" : \"Pinger\",
\"node\" : \"nameofnode\",
\"type\" : \"ICMP\",
\"resource\" : \"C:\",
\"severity\" : \”0\",
\"description\" : \"No ping to host\",
}
]
}
I am trying with this :
$jsonreqUP=#{
records= #(
#{
source="Pinger"
node= $i
type="ICMP"
resource="switch"
severity=0
description="No ping to host $i"
}
)
}
Invoke-RestMethod -Uri http://justasite.com/jsonv2 -Headers #{Authorization = "Basic $base64AuthInfo" } -Credential $creds -Method POST -Body $jsonreqUP -ContentType "application/json"
I am getting error : Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
$i hold a hostname variable.
What is wrong with my transformation?
Many thnaks in advance!
After some reading found that the I am missing| ConvertTo-Json -Depth 4 after the last closng } :)
We're using ADO Server 2019 and as part of a larger project I need to upload some emails to the ADO environment to attach to work items. I've already figured out that you first need to upload the attachment, pass over the attachment ID to the work item patch request and add the relationship from the work item end however what I can't for the life of me figure out is where to pick the actual email or any item up to upload.
The example that's given within the MS docs shows you how to post an upload but it uploads nothing, it just creates a blank page.
POST https://{instance}/fabrikam/_apis/wit/attachments?fileName=textAsFileAttachment.txt&api-version=5.0
A body for the request needs to be built to define where the attachment is from what I can gather however there isn't any kind of documentation around this for simply posting it via HTTP.
We're using Blue Prism so using C# is an option but not ideal.
Thanks in advance.
Please follow the steps below:
1.Upload a text file
POST https://{instance}/fabrikam/_apis/wit/attachments?fileName=textAsFileAttachment.txt&api-version=5.0
Request Body: "User text content to upload"
2.You will get a response like:
{
"id": "6b2266bf-a155-4582-a475-ca4da68193ef",
"url": "https://fabrikam:8080/tfs/_apis/wit/attachments/6b2266bf-a155-4582-a475-ca4da68193ef?fileName=textAsFileAttachment.txt"
}
Copy this url from the response.
3.Add an attachment to work items:
POST https://{instance}/fabrikam/_apis/wit/attachments?fileName=textAsFileAttachment.txt&api-version=5.0
Request body:
[
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": "https://fabrikam:8080/tfs/_apis/wit/attachments/6b2266bf-a155-4582-a475-ca4da68193ef?fileName=textAsFileAttachment.txt",
"attributes": {
"comment": "Spec for the work"
}
}
}
]
Replace the url of the request body.
You have to pass a file content if you create a new attachment. Upload a binary file
POST
https://dev.azure.com/fabrikam/_apis/wit/attachments?fileName=imageAsFileAttachment.png&api-version=6.1-preview.3
"[BINARY FILE CONTENT]"
Here is an example through Powershell:
$user = ""
$token = "<personal access token>"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
$org = "org_name"
$teamProject = "teamproject"
$wiId = "work item Id"
$folderPath = "c:/temp"
$fileName = "some_file.zip"
$createAttachmetUrlTemplate = "https://dev.azure.com/$org/$teamProject/_apis/wit/attachments?fileName={fileName}&api-version=5.0"
$updateWIUrlTemplate = "https://dev.azure.com/$org/_apis/wit/workitems/{id}?api-version=5.0"
$wiBodyTemplate = "[{`"op`": `"add`",`"path`": `"/relations/-`",`"value`": {`"rel`": `"AttachedFile`",`"url`": `"{attUrl}`", `"attributes`": {`"comment`": `"Spec for the work`"}}}]"
function InvokePostRequest ($PostUrl, $body)
{
return Invoke-RestMethod -Uri $PostUrl -Method Post -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Body $body
}
function InvokePatchRequest ($PatchUrl, $body)
{
return Invoke-RestMethod -Uri $PatchUrl -Method Patch -ContentType "application/json-patch+json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Body $body
}
$bytes = [System.IO.File]::ReadAllBytes("$folderPath/$fileName")
$createAttachmetUrl = $createAttachmetUrlTemplate -replace "{filename}", $fileName
$resAtt = InvokePostRequest $createAttachmetUrl $bytes
$updateWIUrl = $updateWIUrlTemplate -replace "{id}", $wiId
$wiBody = $wiBodyTemplate -replace "{attUrl}", $resAtt.url
InvokePatchRequest $updateWIUrl $wiBody
Converting a very simple Plaid API curl data request to a powershell invoke-webrequest
what works:
curl -X POST https://tartan.plaid.com/balance \
-d client_id=client-id-value \
-d secret=secret-value \
-d access_token=access-token-value
What I'm trying unsuccessfully in Powershell
#test powershell api call
$hash = #{ client_id = "client-id-value";
secret = "secret-value"
access_token = "access-token-value"
}
$JSON = $hash | convertto-json
#Invoke-WebRequest -uri "https://tartan.plaid.com/balance" -Method POST -Body $JSON
This returns a plaid error 1100 (client id missing), so I know some API functionality is working, but it's not parsing input data correctly.
My biggest misunderstanding is how to translate a "curl -data" value into the proper Powershell parameter.
Is this a header value, body value? etc.
Unless the target url expects the POST body to be in JSON format, skip the ConvertTo-JSON step completely.
When the chosen HTTP method is POST, Invoke-WebRequest will automatically take all the keys in the hashtable supplied to the -Body parameter and construct a body payload similar to that of curl -d:
$POSTParams = #{
client_id = "client-id-value"
secret = "secret-value"
access_token = "access-token-value"
}
Invoke-WebRequest -Uri "https://tartan.plaid.com/balance" -Method POST -Body $POSTParams
I'm writing a powershell script to call a RESTful API and I need to parse the response. I'm having trouble parsing the response because there isn't a key name to the array. The API just returns contents of an array:
[
{
"ProfileId": "b9b4bf0b-fea3-4464-af91-b79b521d36ba",
"SourcePhoneNumber": "8880001111",
"FirstName": "Peter"
},
{
"ProfileId": "b9b4bf1b-cta3-4464-af91-b68c521d36ba",
"SourcePhoneNumber": "8660001111",
"FirstName": "Fred"
}
]
Here's how I'm calling the API and getting the response:
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("content-type", "application/json")
$headers.Add("Accept-Language", "en-US")
$headers.Add("Authorization", "OAuth $AccessToken")
$response = Invoke-RestMethod "$($privateApiUrl)/api/v1/profiles" -Headers $headers -Method Get -ErrorVariable RestError -ErrorAction SilentlyContinue
if ($RestError)
{
$HttpStatusCode = $RestError.ErrorRecord.Exception.Response.StatusCode.value__
$HttpStatusDescription = $RestError.ErrorRecord.Exception.Response.StatusDescription
Throw "Http Status Code: $($HttpStatusCode) `nHttp Status Description: $($HttpStatusDescription)"
}
else {
Write-Host $response
#Need to parse the first ProfileId out of the response here
$json = ConvertTo-Json -InputObject #( $response )
Write-Host $json[0].ProfileId #This outputs nothing
$response | Out-File -FilePath c:\response2.txt
}
The 2nd to last line "Write-Host $json[0]... is where I'm looking to access the ProfileID.
The response is getting written to c:\response2.txt so I know the API request is working and I'm getting good data back from API call.
So what am I doing wrong in accessing the ProfileId of the objects?
As TessellatingHeckler stated - i just needed to not convert it to json and use $response[0].ProfileId