Make a GET web request from Powershell that includes a body - rest

I'm trying to query Elasticsearch from PowerShell using Invoke-WebRequest. Elasticsearch requires that the GET request have a body which iwr forbids. Is there a workaround or something? Maybe some other program that allows this? curl on POSIX allows this. I know it's not standard, but take it up with Elasticsearch.
Here's what I tried:
Invoke-WebRequest http://localhost:9200/index* -Body '{
"size": 1,
"sort": [
{ "timestamp": {"order": "asc"}}
],
"query": {
<query here>
}
}' -Method GET
This returned:
Invoke-WebRequest : Cannot send a content-body with this verb-type.
Thanks.

Related

Grafana API script to create new datasource failing

I'm learning both Grafana, AND how to interact with APIs in Powershell. I was able to use the Grafana HTTP API to create a dashboard, however I cannot get the same API to create a Datasource. My code is as follows:
$header = #{"Authorization" = "Bearer apikey="}
$createDatasourceUri = "http://localhost:3000/api/datasources"
$createDatasourcejson = #'
{
"datasource": {
"name": "prometheusApiTest",
"type": "prometheus",
"url": "http://localhost:9090",
"access": "proxy",
"basicAuth": false,
"isDefault": true
}
}
'#
$datasourceParameters = #{
Method = "POST"
URI = $createDatasourceUri
Body = $createDatasourcejson
Headers = $header
ContentType = "application/json"
}
Invoke-RestMethod #datasourceParameters
I am presented with the following error:
Invoke-RestMethod : [{"fieldNames":["Name"],"classification":"RequiredError","message":"Required"},{"fieldNames":["Type"],"classification":"RequiredError","message":"Required"},{"fieldNames":["Access"],"classificat
ion":"RequiredError","message":"Required"}]
I do not know what's going on. Anything I can find about this error says I need to specify the ContentType as "application/json", but I've very clearly done so. I do receive data when I do a "GET" on that API endpoint, and even copying the data that gets returned still results in the above error. I'm at a complete loss, as this same code worked to create a dashboard (albeit with the right json payload for a dashboard). Any ideas?
The Grafana docs for the Datasource API only has the datasource element in the response, not the initial call. Line 5 of my code, and the subsequent {} for that element, are not needed, and the script functions with those lines removed.

Unable to link a work item to the test results based on the document

When I was following this document Publish Test Results task
I didn't find any field to link a work item to a test case. Do I need to call an api to do this? Or is there any field that isn't in the document?
Thanks!
We could add the work item in the test run result summary page.
In the build summary page->click the tab test->select the test result, we could see the run id and resultId in the URL
Open Test Plans->click the tab Runs->select the test run and open it->click the tab Test results and open it->we could see the button Bug->click it, then we could select create new bug or add existing bug. You could check the pic below.
Update1
We could do this via REST API to add work item.
Sample:
PATCH https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/results?api-version=6.0
Request Body:
[
{
"id": {Result ID},
"state": "Completed",
"comment": "{Comment}",
"associatedBugs": [
{
"id": {Bug ID}
}
]
}
]
Then we could check it in the UI or this REST API
Sample:
GET https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/results/{testCaseResultId}?detailsToInclude=workItems&api-version=6.0-preview
Note: We could get test run ID in the task publish test result log. We could add power shell task and enter the script to add the work item in the pipeline.
Power shell script sample:
$connectionToken="{PAT}"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$Url = "https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/results?api-version=6.0"
$Body = #"
[
{
"id": {Result ID},
"state": "Completed",
"comment": "{Comment}",
"associatedBugs": [
{
"id": {Bug ID}
}
]
}
]
"#
$Result = Invoke-RestMethod -Uri $Url -ContentType "application/json-patch+json" -Body $Body -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method PATCH

Skip stages is not working using azure devops rest api

I have a very basic pipeline with 4 stages, for prod stage i want to run from separate pipeline . I was trying to use build queue rest api as per documentation and using below payload
{
"stagesToSkip": [
"Build"
],
"definition":
{
"id": "24"
},
"resources": {
"repositories": {
"self": {
"refName": "refs/heads/master"
}
}
},
"variables": {}
}
I got this payload when i manually run the build by selecting only one stage and run it works as expected as highlighted but whn i use the rest api with the same request payload , it runs both the stages.
any pointers what i'm doing wrong??
You can use Run Pipeline rest api to skip stages.
POST https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipelineId}/runs?api-version=6.0-preview.1
See below example in powershell script:
$url="https://dev.azure.com/{org}/{proj}/_apis/pipelines/{pipelineId}/runs?api-version=6.0-preview.1"
$PAT='personal access token'
$body='{
"stagesToSkip":[ "Test" ]
}'
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$result1 = Invoke-RestMethod -Uri $url -Headers #{authorization = "Basic $base64AuthInfo"} -Method post -Body $body -ContentType "application/json"
See below test result. The stage was successfully skipped.

Using GoPhish API in Powershell to Launch Campaigns

currently i'm attempting to setup GoPhish to launch campaigns through a Windows PowerShell script using it's API. The issue that i'm running into that is i'm getting this error.
Invoke-WebRequest : { "message": "Invalid JSON structure", "success": false, "data": null }
The thing is I have triple checked my JSON structure and it doesn't show any errors in JSON formatting checkers. So my question is if there are any errors in the code I have below for actually pushing these campaigns via PowerShell.
$jsonString = #"
{
"name":"Test6",
"template":{
"name":"Test"
},
"url":"http://redacted",
"page":{
"name":"Test"
},
"smtp":{
"name":"Test SMTP"
},
"launch_date":"2019-25-07T08:20:00+00:00",
"send_by_date":null,
"groups":{
"name":"Test Group"
}
}
"#
Invoke-WebRequest -Uri https://redacted/api/campaigns/?api_key=redacted -Method POST -Body $jsonString
So if you see any errors in what I have an could help me out, that'd be awesome. The API documentation shows that it should be in this format
{
"name":"CC Example Campaign",
"template":{"name":"Example Template"},
"url":"http://localhost",
"page":{"name":"Example Landing Page"},
"smtp":{"name":"Example Sending Profile"},
"launch_date":"2018-10-08T16:20:00+00:00",
"send_by_date":null,
"groups":[{"name":"Example Group"}]
}

how to create an issue in jira via rest api?

Is it possible to create an issue in jira using REST api? I didn't find this in the documentation (no POST for issues), but I suspect it's possible.
A wget or curl example would be nice.
POST to this URL
https://<JIRA_HOST>/rest/api/2/issue/
This data:
{
"fields": {
"project":
{
"key": "<PROJECT_KEY>"
},
"summary": "REST EXAMPLE",
"description": "Creating an issue via REST API",
"issuetype": {
"name": "Bug"
}
}
}
In received answer will be ID and key of your ISSUE:
{"id":"83336","key":"PROJECT_KEY-4","self":"https://<JIRA_HOST>/rest/api/2/issue/83336"}
Don't forget about authorization. I used HTTP-Basic one.
The REST API in JIRA 5.0 contains methods for creating tasks and subtasks.
(At time of writing, 5.0 is not yet released, although you can access 5.0-m4 from the EAP page. The doco for create-issue in 5.0-m4 is here).
As of the latest released version (4.3.3) it is not possible to do using the REST API. You can create issues remotely using the JIRA SOAP API.
See this page for an example Java client.
This is C# code:
string postUrl = "https://netstarter.jira.com/rest/api/latest/issue";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("JIRAMMS:JIRAMMS"));
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = #"{""fields"":{""project"":{""key"": ""JAPI""},""summary"": ""REST EXAMPLE"",""description"": ""Creating an issue via REST API 2"",""issuetype"": {""name"": ""Bug""}}}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
To answer the question more direct, i.e. using cURL.
To use cURL to access JIRA REST API in creating a case, use
curl -D- -u <username>:<password> -X POST --data-binary "#<filename>" -H "Content-Type: application/json" http://<jira-host>/rest/api/2/issue/
And save this in your < Filename> (please edit the field per your Jira case) and save in the folder you call the cURL command above.
{
"fields": {
"project":
{
"key": "<PROJECT_KEY>"
},
"summary": "REST EXAMPLE",
"description": "Creating an issue via REST API",
"issuetype": {
"name": "Bug"
}
}
}
This should works. (note sometimes if it errors, possibly your content in the Filename is incorrect).
Now you can use REST + JSON to create issues.
To check which json fields you can set to create the issue use:
https://jira.host.com/rest/api/2/issue/createmeta
For more information please see the JIRA rest documentation:
https://docs.atlassian.com/jira/REST/6.2.4/
To send the issue data with REST API we need to construct a valid JSON string comprising of issue details.
A basic example of JSON string:
{“fields” : { “project” : { “key” : “#KEY#” } , “issuetype” : { “name” : “#IssueType#” } } }
Now, establish connection to JIRA and check for the user authentication.
Once authentication is established, we POST the REST API + JSON string via XMLHTTP method.
Process back the response and intimate user about the success or failure of the response.
So here JiraService being an XMLHTTP object, something like this will add an issue, where EncodeBase64 is a function which returns encrypted string.
Public Function addJIRAIssue() as String
With JiraService
.Open "POST", <YOUR_JIRA_URL> & "/rest/api/2/issue/", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Authorization", "Basic " & EncodeBase64
.send YOUR_JSON_STRING
If .Status <> 401 Then
addJIRAIssue = .responseText
Else
addJIRAIssue = "Error: Invalid Credentials!"
End If
End With
Set JiraService = Nothing
End Sub
You can check out a complete VBA example here
In order to create an issue, set a time estimate and assign it to yourself, use this:
Generate an Atlassian token
Generate & save a base64-encoded auth token:
export b64token="$(echo "<your_email>:<generated_token>" | openssl base64)"
Make a POST request:
curl -X POST \
https://<your_jira_host>.atlassian.net/rest/api/2/issue/ \
-H 'Accept: */*' \
-H 'Authorization: Basic $b64token \
-d '{
"fields":{
"project":{
"key":"<your_project_key (*)>"
},
"issuetype":{
"name":"Task"
},
"timetracking":{
"remainingEstimate":"24h"
},
"assignee":{
"name":"<your_name (**)>"
},
"summary":"Endpoint Development"
}
}'
Remarks:
(*) Usually a short, capitalized version of the project description such as: ...atlassian.net/projects/UP/.
(**) if you don't know your JIRA name, cURL GET with the same Authorization as above to https://<your_jira_host>.atlassian.net/rest/api/2/search?jql=project=<any_project_name> and look for issues.fields.assignee.name.
Just stumbling on this and am having issues creating an issue via the REST API.
issue_dict = {
'project': {'key': "<Key>"},
'summary': 'New issue from jira-python',
'description': 'Look into this one',
'issuetype': {'name': 'Test'},
}
new_issue = jira.create_issue(issue_dict)
new_issue returns an already existing issue and doesn't create one.