Querying GraphQL with PowerShell - powershell

So I've been trying to query GraphQL from PowerShell. Everything looks perfect in a cmd, but I cannot make it work in PS, see, I have this code so far:
$oAuth2TokenUrl = "https://api.cloudflare.com/client/v4/zones/0000/analytics/dashboard"
$accessKey = '1111'
$Cloudflare_Oauth_Header = #{
"Authorization" = "Bearer $accessKey";
}
$query = #'
{ "query": "query { viewer {
zones(filter: {zoneTag: 0000}) {
httpRequests1mGroups(orderBy: [datetimeMinute_ASC], limit: 1000, filter: {datetime_geq: "2019-09-08T20:00:00Z", datetime_lt: "2019-09-08T20:02:00Z"}) {
dimensions {datetimeMinute}
sum {
browserMap {
pageViews
uaBrowserFamily
}
bytes
cachedBytes
cachedRequests
contentTypeMap {
bytes
requests
edgeResponseContentTypeName
}
clientSSLMap {
requests
clientSSLProtocol
}
countryMap {
bytes
requests
threats
clientCountryName
}
encryptedBytes
encryptedRequests
ipClassMap {
requests
ipType
}
pageViews
requests
responseStatusMap {
requests
edgeResponseStatus
}
threats
threatPathingMap {
requests
threatPathingName
}
}
uniq {
uniques
}
}
}
} }" }
'#
$Cloudflare_zone = Invoke-RestMethod -Method Post -Headers $Cloudflare_Oauth_Header -ContentType "application/json; charset=utf-8" -Uri $oAuth2TokenUrl -Body $query
And I keep getting the error Invoke-RestMethod : The remote server returned an error: (501) Not Implemented.
But if I curl in cmd it returns what is expected and no error is shown.
Please let me know if you need more details.

I would suggest getting a simple query to work first, and then expanding it to be more complex. Also, be sure to use -ContentType "application/json" which some GraphQL servers require. The switch -UseBasicParsing can also help avert error but probably isn't the issue here. Lastly, you might also need a trailing slash in the URL: E.g., http://127.0.0.1:8080/graphql/.
This thread might also help:
https://www.reddit.com/r/PowerShell/comments/b9jasa/query_graphql_with_powershell/

I have a GraphQL module for PowerShell with a single function (Invoke-GraphQLQuery that may help you here). Link: https://github.com/anthonyg-1/PSGraphQL
But I definitely agree that you should start with a much smaller query. Check out some of the examples in my readme or run Get-Help Invoke-GraphQLQuery for more.

Related

Pass Azure Automation Runbook Webhook Body to Logic Apps

I have created a webhook in Azure Automation. I am looking to pass the body when the webhook is called to a logic app. Please see the powershell code designed of runbook.
param
(
[Parameter(Mandatory=$false)]
[object] $WebhookData
#[string] $jobId
)
if ($WebhookData.RequestBody) {
$names = (ConvertFrom-Json -InputObject $WebhookData.RequestBody)
Write-Output $names
$webhookName = $WebhookData.WebhookName
$logicappURI = "https://logicapp/api/test/triggers/manual/invoke/properties/"+$webhookName+"?api-version=2022-05-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig={signature_certificate"
$response = Invoke-WebRequest -Method GET -Uri $logicappURI
}
else {
Write-Output "Hello World!"
}
Currently I am able to call the logic app and pass the webhook name, but the i would like to pass the complete request body. Below is the request body for webhook.
{
"WebhookName": "wh-test-webhook-ext-cus-001",
"RequestBody": "[{\"Name\": \"Hawaii\" },{\"Name\": \"Seattle\"},{ \"Name\": \"Florida\"}]",
"RequestHeader": {
"Connection": "Keep-Alive",
"Host": "14304127-e302-4499-b819-8ac4493555e9.webhook.cus.azure-automation.net",
"User-Agent": "Mozilla/5.0",
"x-ms-request-id": "47ca3f1a-2418-4553-94c4-9f20c2095c80"
}
}
The logic app is designed to trigger when an HTTP request is recieved. As shown in the image I am passing passing webhook name. Similarly is there a way I can pass the complete ReuqestBody.
Thanks in advance.
Logic App Design

How to add branch policies using powershell Invoke RestMethod

We have PowerShell script that will automate creating branch.
Now we are trying to automate branch policies using api using PowerShell Invoke-RestMethod.
We have option to manually add policies using cross repository policies, but we have build validation enabled for repositories which is different for each repo.
I'm able to get the policy configurations using GET https://dev.azure.com/$organization/$project/_apis/policy/configurations/repo=$repoName&api-version=6.0
But don't know how to get the get the particular value and add policies.
You can use the Configurations - Create Rest API:
POST https://dev.azure.com/{organization}/{project}/_apis/policy/configurations/{configurationId}?api-version=6.1-preview.1
In the body you specify the branch policy you want to add, for example - build policy:
{
"isEnabled": true,
"isBlocking": false,
"type": {
"id": "0609b952-1397-4640-95ec-e00a01b2c241"
},
"settings": {
"buildDefinitionId": 5,
"scope": [
{
"repositoryId": null,
"refName": "refs/heads/feature",
"matchKind": "prefix"
}
]
}
}
In the above body you add branch (build) policy to branch feature that requires build 5 to pass.
You cans see all the available policy types in the Types - List api.
To add the Build validation in Branch Policy, you could refer to the following PowerShell Sample:
$token = "PAT"
$url="https://dev.azure.com/{OrganizationName}/{ProjectName}/_apis/policy/configurations?api-version=6.1-preview.1"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$JSON = #'
{
"type":{
"id":"0609b952-1397-4640-95ec-e00a01b2c241"
},
"revision":1,
"isDeleted":false,
"isBlocking":true,
"isEnabled":true,
"settings":{
"buildDefinitionId":592,
"displayName":null,
"manualQueueOnly":false,
"queueOnSourceUpdateOnly":true,
"validDuration":720,
"scope":[
{
"repositoryId":"RepoID",
"refName":"refs/heads/BranchName",
"matchKind":"Exact"
}
]
}
}
'#
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method POST -Body $JSON -ContentType application/json
You could refer to this doc about Configurations - Create and Repositories - List
Result:

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.

PowerShell GraphQL Mutation Parsing Error

I'm querying the Monday API v2 (https://monday.com/developers/v2) I'm getting stuck in getting the PowerShell query to work, the script is below:
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
$url = "https://api.monday.com/v2/"
$hdr = #{ }
$hdr.Add("Authorization", "redacted")
$hdr.Add("Content-Type", "application/json")
$bodytxt = '{"query":"mutation{change_column_value (board_id: 528033866, item_id: 574335355, column_id: \"status_1\", value: "{\"index\": 1}") {id}}"}'
$response = Invoke-WebRequest -Uri $url -Headers $hdr -Method Post -body $bodytxt
Write-Host $response
And it keeps returning
{"errors":[{"message":"Parse error on \": 1}\" (STRING) at [1, 110]","locations":[{"line":1,"column":110}]}],"account_id":5305133}
The mutation query in Postman works fine
change_column_value (board_id: 528033866, item_id: 574335355, column_id: "status_1", value: "{\"index\": 1}"){id}
}
I have tried working with what quotes are escaped, but I still haven't been able to get it to run succesfully. I was referencing the tips here https://www.reddit.com/r/PowerShell/comments/b9jasa/query_graphql_with_powershell/
Any thoughts on how to fix this error?
EDIT: Sorry forgot to add the current query (not mutation) that works fine through Powershell
$bodytxt = '{"query":"{ boards (ids: 528033866) { groups (ids: \"group_title\"){ items () { id name updates () { body } column_values () { id title value text } } title } } }"}'
The easiest way to create a GraphQL query is
create a hashtable with HERE-STRINGS
convert it to a JSON string with ConvertTo-Json.
$bodytxt = #{"query" = #'
mutation {
change_column_value(
board_id: 123123
item_id: 456456
column_id: "status1"
value: "{\"index\":1}"
) {
id
}
}
'#
} | ConvertTo-Json
White spaces inside #'...'# are optional.
reply to this comment
it should always work in the API call with the GraphQL?
I think it depends on services, but in most cases, yes. application/json is the GraphQL default content type for the request body.
and for monday.com
Be sure to use the application/json content type

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"}]
}