Could you help me?
I am trying to create an issue in Jira using the Powershell Invoke-WebRequest cmdlet. And I am getting 400 Bad Request error.
I was able to send a successful request using Postman, so I made sure the body syntax is correct and I have sufficient rights.
My code:
$body = #{
"fields" = #{
"project"=
#{
"key"= "ProjectKey"
}
"summary"= "Test"
"description"= "Test"
"issuetype" =#{
"id"= "10705"
}
"priority"= #{
"id"= "18"
}
"reporter"= #{"name"= "MyName"}
}
}
$Headers = #{
Authorization = "Basic QWxla0Zblablablablablablabla" #I took it from Postman
}
$restapiuri = "https://jira.domain.com/rest/api/2/issue"
Invoke-RestMethod -Uri $restapiuri -ContentType "application/json" -Body $body -Method POST -Headers $Headers
for example, I can successfully execute
Invoke-RestMethod "https://jira.domain.com/rest/api/2/issue/createmeta" -Headers $Headers
I've already spent a lot of time-solving this problem, but still can't create an issue.
Any help, please ๐๐๐
For basic authentication with Jira SERVER, the credentials need to be supplied within the header in Base64 encoding, which you need to do before supplying it via the Powershell Invoke-WebRequest method. Here's how to do it:
$username = "The username here"
$password = "The password or token here"
# Convert the username + password into a Base64 encoded hash for basic authentication
$pair = "${username}:${password}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$headers = #{ Authorization = "Basic $base64" }
Next, in PowerShell, if you build the body of the request as a table, like you've shown, don't don't need to wrap the table elements with inverted commas, just leave them as is, but you do need to convert the table to JSON format before submitting it, like this:
$body = #{
fields = #{
project = #{
key = "ProjectKey"
}
issuetype = #{
id = "10705" # Or refer to the Issue type by its name eg. name = "Story"
}
summary = "Test"
}
}
# Convert the body to JSON format
$body = $body | ConvertTo-Json -Depth 50
I'm assuming your $Uri string contains an actual URL to a Jira Server, not the example 'jira.domain.com'
Start with a simple request in the body, like the one I've shown, that contains only the minimum required to create the Issue, which will check your basic code is working before making the request more complex.
Related
I'm creating a log of attempted posts to an API. The API key is stored in a simple hash table and passed via Invoke-WebRequest:
$headers = #{ 'x-api-key' = 'ABC123DEF456GHI789' }
Try {
[Net.ServicePointManager]::SecurityProtocol = 'tls12, tls11'
$apiResponse = Invoke-WebRequest -Uri $url -Method $method -Headers $headers -Body $body
$status = $apiResponse.StatusCode
$statusDescription = $apiResponse.StatusDescription
} Catch {
$status = $_.Exception.Response.StatusCode.value__
$statusDescription = $_.Exception.Response.StatusDescription
}
I want to obscure the header key in the log, so I created and modified a new variable.
$obscured = $headers | ConvertTo-Json -depth 100 | ConvertFrom-Json
$obscured.'x-api-key' = $obscured.'x-api-key'.Substring(0,2) + '...' + $obscured.'x-api-key'.Substring($obscured.'x-api-key'.Length-2,2)
$logresults += [PSCustomObject]#{
status = $status
statusDescription = $statusDescription
url = $url
method = $method
header = $obscured
body = ConvertFrom-JSON $body
}
I want to retain the header's structure as a key/value pair in the log. The extra steps prepping a new variable seem wasteful. Does PowerShell have a way to change the header key value upon assignment to the PSCustomObject?
AFAIK, there is no easy way to obscure strings (or objects) in PowerShell or even .Net, see my related purpose: #16921 Add [HiddenString] Class. The only thing that exists is the gone crazy SecureString Class with difficult methodes to convert from a string and reveal string (as that is not secure). Besides, the SecureString might get obsolete (as it appears less secure than intended) and possibly replaced by a shrouded buffer which is even more difficult to use for obscuring information (if even possible in PowerShell).
Anyways, in the HiddenString idea you might do something like this:
$ApiKey = [HiddenString](Read-Host -AsSecureString 'Enter Api key:')
See also: How to encrypt/hide ClearText password in PowerShell Transcript
$Headers = #{
'Accept' = 'application/json'
'X-My-Header' = 'Hello World'
'x-api-key' = $ApiKey
}
$apiResponse = Invoke-WebRequest -Uri $url -Method $method -Headers $($Headers.'x-api-key' = $ApiKey.Reveal(); $Headers) -Body $body
$logresults += [PSCustomObject]#{ # Avoid +=, see: https://stackoverflow.com/a/60708579/1701026
status = $status
statusDescription = $statusDescription
url = $url
method = $method
header = $Headers
body = ConvertFrom-JSON $body
}
I am trying to use the LastPass Enterprise API to automate the creation of new users in our system using Powershell. I cannot seem to get the call to the API correct in my code. I am almost certain it has something to do with the "data" object. This is the batch object I am passing through the body.
$lastPassObject = #{
cid = "G1TUROWN";
provhash = "N0TM!NE";
cmd = "batchadd";
data = #(
{
username = $email;
fullname = $firstName + " " + $lastName;
password = "Toys4Trucks22!";
password_reset_required = "true";
}
)
}
Here is my API call
Invoke-RestMethod -Uri "https://lastpass.com/enterpriseapi.php" -Method Post -Body $lastPassObject -ContentType "application/json"
Followed by the Error I am receiving
Reference to the API: https://support.lastpass.com/help/add-new-users-via-lastpass-api
You need to convert your body to json before sending it.
Also, you put your Data section in a scriptblock within an array.
This need to be a hashtable, not a scriptblock.
$lastPassObject = #{
cid = "G1TUROWN";
provhash = "N0TM!NE";
cmd = "batchadd";
data = #(
# This need to be an hashtable. You were missing the #
#{
username = $email;
fullname = $firstName + " " + $lastName;
password = "Toys4Trucks22!";
password_reset_required = $true;
}
)
}
$Body = $lastPassObject | ConvertTo-Json
Invoke-RestMethod -Uri "https://lastpass.com/enterpriseapi.php" -Method Post -Body $Body -ContentType "application/json"
If you still have issues after that, make sure to check what the actual json look like (after ConvertTo-Json) so you know exactly what you are sending and can spot more easily discrepancies. For instance, when I first did it, I immediately saw that the data section was all wrong, formatting wise and spotted the missing # because of that.
Also, still by looking at the converted json and the example from their doc, you can see that password_reset_required is a boolean. I changed your "true" to $true so that the correlating json would be what was expected.
I am working with the Google API to automate tasks for distribution groups.
I understand how to send individual requests, but I want to be able to send BatchRequests, and this seems to be a challenge as the format is not consistent like for example all JSON so i can convert the body once and make my request.
I am reading through the documentation from Google and I cant figure out how to achieve that with Powershell.
https://developers.google.com/admin-sdk/directory/v1/guides/batch
I see there is already a .NET library for that, but I struggle to understand how to use it.
https://googleapis.dev/dotnet/Google.Apis/latest/api/Google.Apis.Requests.BatchRequest.html
I cant understand how I can do nested HTTP request inside a HTTP request with PowerShell.
I have no idea how I can even write it, so here is a draft that I am thinking over, and I will be editing throughout this post.
$batchUrl = 'https://www.googleapis.com/batch/admin/directory_v1'
$header = #{
"Content-type" = "multipart/mixed; boundary=batch_test"
"Authorization" = "Bearer <token>"
}
$psBody = [ordered] #{
method = "POST /admin/directory/v1/groups/vtest#gs.vasil.com/members"
"content-type" = "application/json"
email = "vas#gs.vasil.com"
role = "MEMBER"
}
$JSONbody = $psBody | ConvertTo-Json
Invoke-RestMethod -Uri $batchUrl -Method POST -Headers $header -Body $JSONbody
I really want to understand that OData structure, any documentation/guide reference are welcome.
I figured it out, the format needed was literally what Google posted, therefore I just had to adjust the body to what I want.
The example bellow is just Prove of Concept and would need some functions to automate the population from an Array.
$URL = 'https://www.googleapis.com/batch/admin/directory_v1'
$boundary = [System.Guid]::NewGuid().ToString();
$LF = "`r`n";
$header = #{
"Content-type" = "multipart/mixed; boundary=$boundary"
"Authorization" = "Bearer <token>"
}
$request1 = [pscustomobject][ordered]#{
email = "vas1#gs.vasil.com"
role = "MEMBER"
} | ConvertTo-Json
$request2 = [pscustomobject][ordered]#{
email = "vas2#gs.vasil.com"
role = "MEMBER"
} | ConvertTo-Json
$nestedBody = (
"--$boundary",
"Content-Type: application/http$LF",
"POST /admin/directory/v1/groups/vtest#gs.vasil.com/members",
"Content-Type: application/json$LF",
"$($request1)$LF",
"--$boundary--",
"Content-Type: application/http$LF",
"POST /admin/directory/v1/groups/vtest#gs.vasil.com/members",
"Content-Type: application/json$LF",
"$($request2)$LF",
"--$boundary--"
) -join $LF
$sendRequest = #{
Uri = $URL
header = $header
Method = "Post"
Body = $nestedBody
}
Invoke-RestMethod #sendRequest
The way I got to that conclusions was by installing the Fiddler Proxy and see how my request look like in practice, check screenshot bellow.
Azure DevOps Services REST API 5.0 - Wiki Pages
I'm trying to dynamically update an Azure DevOps Wiki page with the newest commits on top whenever a change is introduced to a repository.
When I try to PUT the commit history into a Wiki page the content field within the body is empty.
The request is done via Powershell and looks like this:
function postToWiki($Commits) {
$wikiUrl = "https://dev.azure.com/$organization/$project/_apis/wiki/wikis/Ekonomiredovisning.wiki/pages?path=MyWikiPage&api-version=5.0"
$Etag = getWikiPageVersion
$headers = #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN";
'If-Match' = $Etag}
$body = #{ content = $Commits }
$json = $body | ConvertTo-Json
Invoke-WebRequest -Uri $wikiUrl -Headers $headers -Body $json -ContentType "application/json" -Method Put
}
Additional information that can be useful:
It works when I send simpler strings like "Hello"
The JSON being sent is valid according to https://jsonlint.com/.
The $Commit variable is pretty huge, up to 6000 lines.
I have the same problem today. My body contained special HTML caracters wich are not escaped in the request.
Try to escape the special chars (รฉรจ...).
In PowerShell, you can use the following assembly:
Add-Type -AssemblyName System.Web
$encodedBody = [System.Web.HttpUtility]::HtmlEncode($Commits)
Result:
# Construct the wiki REST URI
# $uri = $WikiUri +$WikiPath + $($contentPackage.version)
$uri = "$($env:WikiUri)$($contentPackage)&api-version=5.0"
# Encode and convert to json
Add-Type -AssemblyName System.Web
$encodedContent = [System.Web.HttpUtility]::HtmlEncode($content)
$data = #{ Content=$encodedContent; } | ConvertTo-Json;
# Set Request
$params = #{uri = "$($uri)";
Method = 'PUT';
Headers = $header;
ContentType = "application/json";
Body = $data;
}
# Call
Invoke-WebRequest #params
I'm trying to create an event in a calendar in an Office 365 group via powershell.
This is my first experience to do this type of programming so sorry if my question will be very basic :-)
First, I created a simple json file (calendar.json)
{
"start":
{
"dateTime":"2017-03-12T17:00:00.0000000",
"timeZone":"UTC"
},
"end":
{
"dateTime":"2017-03-12T17:30:00.0000000",
"timeZone":"UTC"
},
"responseStatus": {
"response": "None"
},
"iCalUId": "null",
"isReminderOn": false,
"subject": "Test Event created from API"
}
Then I create the event with these steps:
Use a tested powershell function that give me the token
Add header with this code:
$headers = #{}
$headers.Add('Authorization','Bearer ' + $token.AccessToken)
$headers.Add('Content-Type',"application/json")
Because I'm starting now, I convert the json file in an object and then the object in json (I know, it's quite stupid, but I've done so beacuse I have no knowledge of json and how convert without error in powershell code)
$json = ConvertFrom-Json -InputObject (Gc 'C:\Users\mmangiante\OneDrive - Interactive Media S.p.A\Office 365\calendar.json'-Raw)
$body = ConvertTo-Json $json
Call the Invoke-RestMethod
response = Invoke-RestMethod 'https://graph.microsoft.com/v1.0/groups/768afb0c-bafd-4272-b855-6b317a3a9953/calendar/events' -Method Post -Headers $headers -Body $json
What is returned is a 400 bad request.
It's the same error of Sending Microsoft Graph request events returns 400
Given the answer given to that question I modified my code to return the error:
try{$restp=Invoke-RestMethod 'https://graph.microsoft.com/v1.0/groups/768afb0c-bafd-4272-b855-6b317a3a9953/calendar/events' -Method Post -Headers $headers -Body $json
} catch {$err=$_}
$err
like suggested in How do I get the body of a web request that returned 400 Bad Request from Invoke-RestMethod but I found nothing of interest.
The only thing that I found is that, at the time of writing, the Invoke-RestMethod doesn't return the full response as in this https://github.com/PowerShell/PowerShell/issues/2193
I suppose my json is not "well formed", but I don't know why.
Does anyone have a suggestion?
This formatting has worked for me in the past. Let me know if this resolves your issues:
$headers = #{
"Authorization" = ("Bearer {0}" -f $token);
"Content-Type" = "application/json";
}
$body = #{
Name1 = 'Value1';
Name2 = 'Value2';
}
$bodyJSON = $body | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri <API HERE> -Headers $headers -Body $bodyJSON -OutFile $output
Thanks Shawn,
I tried your suggestion but without luck; I have done other test with 2 other api and found discordant results.
The first test is to use the graph api related to contact, creating a contact as in https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/user_post_contacts
I created the powershell representation of the sample json:
$contactbody = #{
givenName = 'Ciccio';
surname = 'Patacca';
emailAddresses = #(
#{
address = 'cicciopatacca#cicciociccio.com'
name = 'Ciccio Patacca'
}
)
businessPhones = (
'+39 555 123 4567'
)
}
and then converted in json
$contactbody = $contactbody | ConvertTo-Json
I retrieved from Azure Portal the object ID related to my user in my company and so I call the rest method:
$response = Invoke-RestMethod 'https://graph.microsoft.com/v1.0/users/e37d2dbe-bdaf-4098-9bb0-03be8c653f7d/contact' -Method Post -Headers $headers -Body $contactbody
The final result is a 400 bad request error.
So, I tried another example and reused some code retrieved from a google search.
This time I copied the powershell json representation as in the sample and converted:
$body = #{"displayName"="ps-blog"; "mailEnabled"=$false; "groupTypes"=#("Unified"); "securityEnabled"=$false; "mailNickname"="ps1" } | ConvertTo-Json
and, as stated in https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/group_post_groups I called the rest method
$response = Invoke-RestMethod 'https://graph.microsoft.com/v1.0/groups' -Method Post -Headers $headers -Body $body
and this worked.
So I thought that the previously powershell representations of the sample with the error were not correctly formed (even if when I printed it they are equal to the samples on the graph api); for test, I rewritten the last powershell of the body as this:
$body = #{
displayName = 'TestGraphGroup';
mailEnabled = $true;
groupTypes = #('Unified')
securityEnabled = $false;
mailNickname = 'TestGraphGroup'
}
$body = $body | ConvertTo-Json
and invoked last method: it worked again.
So, where I'm doing wrong?
A new SDK was released that makes this easier.
Checkout instructions on how to use it here