Functions/Invoke-GraphQLQuery.ps1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 |
function Invoke-GraphQLQuery { <# .SYNOPSIS Sends a query or mutation to a GraphQL endpoint. .DESCRIPTION Sends a query (read operation) or mutation (create, update, delete operation) to a GraphQL endpoint. .PARAMETER Query The GraphQL query or mutation to send to the endpoint. .PARAMETER OperationName A meaningful and explicit name for your GraphQL operation. .PARAMETER Variables Variables expressed as a hash table or JSON string for your GraphQL operation. .PARAMETER Headers Specifies the headers of the web request expressed as a hash table. .PARAMETER Uri Specifies the Uniform Resource Identifier (URI) of the GraphQL endpoint to which the GraphQL query or mutation is sent. .PARAMETER WebSession Specifies a web request session. Enter the variable name, including the dollar sign (`$`). .PARAMETER Raw Tells the function to return JSON as opposed to objects. .PARAMETER ContentType Specifies the ContentType for the Webrequest (Default: "application/json"). Can be used to resolve encoding problems. .PARAMETER Detailed Returns parsed and raw responses from the GraphQL endpoint as well as HTTP status code, description, and response headers. .PARAMETER EscapeHandling Specifies the escape handling mechanism for JSON conversion. Usage of this parameter is only applicable to PowerShell versions 6 and above. .NOTES Query and mutation default return type is a collection of objects. To return results as JSON, use the -Raw parameter. To return both parsed and raw results, use the -Detailed parameter. .EXAMPLE $uri = "https://mytargetserver/v1/graphql" $query = ' query RollDice($dice: Int!, $sides: Int) { rollDice(numDice: $dice, numSides: $sides) }' $variables = ' { "dice": 3, "sides": 6 }' Invoke-GraphQLQuery -Query $query -Variables $variables -Uri $uri Sends a GraphQL query to the endpoint 'https://mytargetserver/v1/graphql' with variables defined in $variables as JSON. .EXAMPLE $uri = "https://mytargetserver/v1/graphql" $query = ' query RollDice($dice: Int!, $sides: Int) { rollDice(numDice: $dice, numSides: $sides) }' $variables = @{dice=3; sides=6} Invoke-GraphQLQuery -Query $query -Variables $variables -Uri $uri Sends a GraphQL query to the endpoint 'https://mytargetserver/v1/graphql' with variables defined in $variables. .EXAMPLE $uri = "https://mytargetserver/v1/graphql" $introspectionQuery = ' query allSchemaTypes { __schema { types { name kind description } } } ' Invoke-GraphQLQuery -Query $introspectionQuery -Uri $uri -Raw Sends a GraphQL introspection query to the endpoint 'https://mytargetserver/v1/graphql' with the results returned as JSON. .EXAMPLE $uri = "https://mytargetserver/v1/graphql" $results = Invoke-GraphQLQuery -Uri $uri Sends a GraphQL introspection query using the default value for the Query parameter (as opposed to specifying it) to the endpoint 'https://mytargetserver/v1/graphql' with the results returned as objects and assigning the results to the $results variable. .EXAMPLE $uri = "https://mytargetserver/v1/graphql" $myQuery = ' query GetUsers { users { created_at id last_seen name } } ' Invoke-GraphQLQuery -Query $myQuery -Uri $uri -Raw Sends a GraphQL query to the endpoint 'https://mytargetserver/v1/graphql' with the results returned as JSON. .EXAMPLE $uri = "https://mytargetserver/v1/graphql" $myQuery = ' query GetUsers { users { created_at id last_seen name } } ' $result = Invoke-GraphQLQuery -Query $myQuery -Uri $uri $result.data.users | Format-Table Sends a GraphQL query to the endpoint 'https://mytargetserver/v1/graphql' with the results returned as objects and navigates the hierarchy to return a table view of users. .EXAMPLE $jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MjAzOTMwMjgsIm5iZiI6MTYyMDM5MzAyNywiZXhwIjoxNjIwMzkzMzI4LCJzdWIiOiJtZUBjb21wYW55LmNvbSIsImp0aSI6ImMwZTk0ZTY0ODc4ZjRlZDFhZWM3YWYwYzViOWM2ZWI5Iiwicm9sZSI6InVzZXIifQ.HaTXDunEjmyUsHs7daLe-AxEpmq58QqqFziydm7MBic" $headers = @{Authorization="Bearer $jwt"} $uri = "https://mytargetserver/v1/graphql" $myQuery = ' query GetUsers { users { created_at id last_seen name } } ' $result = Invoke-GraphQLQuery -Query $myQuery -Headers $headers -Uri $uri $result.data.users | Format-Table Sends a GraphQL query using JWT for authentication to the endpoint 'https://mytargetserver/v1/graphql' with the results returned as objects and navigates the hierarchy to return a table view of users. .EXAMPLE $uri = "https://mytargetserver/v1/graphql" $myMutation = ' mutation MyMutation { insert_users_one(object: {id: "57", name: "FirstName LastName"}) { id } } ' $requestHeaders = @{ "x-api-key"="aoMGY{+93dx&t!5)VMu4pI8U8T.ULO" } $jsonResult = Invoke-GraphQLQuery -Mutation $myMutation -Headers $requestHeaders -Uri $uri -Raw Sends a GraphQL mutation to the endpoint 'https://mytargetserver/v1/graphql' with the results returned as JSON. .EXAMPLE gql -q 'query { users { created_at id last_seen name } }' -u 'https://mytargetserver/v1/graphql' -r Sends a GraphQL query to an endpoint with the results returned as JSON (as a one-liner using aliases). .LINK https://graphql.org/ Format-Table Get-GraphQLVariableList #> [CmdletBinding()] [Alias("gql", "Invoke-GraphQLMutation", "Invoke-GraphQLOperation")] [OutputType([System.Management.Automation.PSCustomObject], [System.String], [GraphQLResponseObject])] Param ( [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $false, Position = 0)][ValidateLength(12, 1073741791)][Alias("Mutation", "Operation", "q", "m", "o")][System.String]$Query = "query introspection { __schema { types { name kind description } } }", [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $false, Position = 1)][ValidateLength(1, 4096)][Alias("op")][System.String]$OperationName, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $false, Position = 2)][ValidateNotNullOrEmpty()][Alias("v", "Arguments")][Object]$Variables, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $false, Position = 3)][Alias("h")][System.Collections.Hashtable]$Headers, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $false, Position = 4)][Alias("u")][System.Uri]$Uri, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $false, Position = 5)][Microsoft.PowerShell.Commands.WebRequestSession]$WebSession, [Parameter(Mandatory = $false, Position = 6)][Alias("AsJson", "json", "r")][Switch]$Raw, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $false, Position = 7)][Alias("ct")][System.String]$ContentType = "application/json", [Parameter(Mandatory = $false, ParameterSetName = "Detailed", Position = 7)][Switch]$Detailed, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $false, Position = 8)][ValidateSet('Default', 'EscapeNonAscii', 'EscapeHtml')][Alias("eh")][System.String]$EscapeHandling = "Default" ) BEGIN { # Return type when using the -Detailed switch: class GraphQLResponseObject { [Int]$StatusCode = 0 [String]$StatusDescription = "" [String]$Response = "" [PSObject]$ParsedResponse = $null [String]$RawResponse = "" [HashTable]$ResponseHeaders = @{ } [TimeSpan]$ExecutionTime [Microsoft.PowerShell.Commands.WebRequestSession]$Session } # Used to determine if running PowerShell Core or earlier: $psMajorVersion = $PSVersionTable.PSVersion.Major } PROCESS { # The object that will ultimately be serialized and sent to the GraphQL endpoint: $jsonRequestObject = [ordered]@{ } # Trim all spaces and flatten $OperationName parameter value and add to $jsonRequestObject: if ($PSBoundParameters.ContainsKey("OperationName")) { $cleanedOperationInput = Compress-String -InputString $OperationName $jsonRequestObject.Add("operationName", $cleanedOperationInput) } # Determine if $Variables is JSON or a HashTable and add to $jsonRequestObject: if ($PSBoundParameters.ContainsKey("Variables")) { $ArgumentException = New-Object -TypeName System.ArgumentException -ArgumentList "Unable to parse incoming GraphQL variables. Please ensure that passed values are either valid JSON or of type System.Collections.HashTable." if ($Variables.GetType().Name -eq "Hashtable") { $jsonRequestObject.Add("variables", $Variables) } elseif ($Variables.GetType().Name -eq "String") { $variableTable = @{ } try { $deserializedVariables = $Variables | ConvertFrom-Json -ErrorAction Stop $deserializedVariables.PSObject.Properties | ForEach-Object { $variableTable.Add($_.Name, $_.Value) } $jsonRequestObject.Add("variables", $variableTable) } catch { Write-Error -Exception $ArgumentException -Category InvalidArgument -ErrorAction Stop } } else { Write-Error -Exception $ArgumentException -Category InvalidArgument -ErrorAction Stop } } # Trim all spaces and flatten $Query parameter value and add to $jsonRequestObject: $cleanedQueryInput = Compress-String -InputString $Query if (($cleanedQueryInput.ToLower() -notlike "query*") -and ($cleanedQueryInput.ToLower() -notlike "mutation*") ) { $ArgumentException = New-Object -TypeName ArgumentException -ArgumentList "Not a valid GraphQL query or mutation. Verify syntax and try again." Write-Error -Exception $ArgumentException -Category InvalidArgument -ErrorAction Stop } # Add $Query $jsonRequestObject: $jsonRequestObject.Add("query", $cleanedQueryInput) # Serialize $jsonRequestObject: [string]$jsonRequestBody = "" try { if ($psMajorVersion -gt 5) { $jsonRequestBody = $jsonRequestObject | ConvertTo-Json -Depth 100 -Compress -EscapeHandling $EscapeHandling -ErrorAction Stop -WarningAction SilentlyContinue } else { $jsonRequestBody = $jsonRequestObject | ConvertTo-Json -Depth 100 -Compress -ErrorAction Stop -WarningAction SilentlyContinue if ($PSBoundParameters.ContainsKey("EscapeHandling")) { Write-Warning -Message "EscapeHandling is not supported for Invoke-GraphQLQuery for the detected PowerShell version." } } } catch { Write-Error -Exception $_.Exception -Category InvalidResult -ErrorAction Stop } [HashTable]$params = @{Uri = $Uri Method = "Post" Body = $jsonRequestBody ContentType = $ContentType ErrorAction = "Stop" UseBasicParsing = $true } if ($PSBoundParameters.ContainsKey("Headers")) { $params.Add("Headers", $Headers) } # Use or establish a web session: $currentSession = "currentSession" if ($PSBoundParameters.ContainsKey("WebSession")) { $params.Add("WebSession", $WebSession) } else { $params.Add("SessionVariable", $currentSession) } if ($PSBoundParameters.ContainsKey("Detailed")) { # Object to be returned for the Detailed parameter: $gqlResponse = [GraphQLResponseObject]::new() # Skip HTTP error checking only when the Detailed parameter is used: if ($PSVersionTable.PSVersion.Major -ge 7) { $params.Add("SkipHttpErrorCheck", $true) } $response = $null try { # Capture the start time: $startDateTime = Get-Date # Execute the GraphQL operation: $response = Invoke-WebRequest @params # Capture the end time in order to obtain the delta for the ExecutionTime property: $endDateTime = Get-Date # Calculate execution time: $gqlResponse.ExecutionTime = (New-TimeSpan -Start $startDateTime -End $endDateTime) } catch { Write-Error -Exception $_.Exception -Category InvalidOperation -ErrorAction Stop } # Populate properties of object to be returned: $gqlResponse.StatusCode = $response.StatusCode $gqlResponse.StatusDescription = $response.StatusDescription $gqlResponse.Response = $response.Content # Attempt to deserialize Content from JSON, if not populate ParsedResponse with a null value: try { $gqlResponse.ParsedResponse = $($response.Content | ConvertFrom-Json -ErrorAction Stop -WarningAction SilentlyContinue) } catch { $gqlResponse.ParsedResponse = $null } $gqlResponse.RawResponse = $response.RawContent if ($PSBoundParameters.ContainsKey("WebSession")) { $gqlResponse.Session = $WebSession } else { $gqlResponse.Session = $currentSession } # Populate ResponseHeaders property: [HashTable]$responseHeaders = @{ } $response.Headers.GetEnumerator() | ForEach-Object { $responseHeaders.Add($_.Key, $_.Value) } $gqlResponse.ResponseHeaders = $responseHeaders return $gqlResponse } else { try { $response = Invoke-RestMethod @params } catch { Write-Error -Exception $_.Exception -Category InvalidOperation -ErrorAction Stop } if ($PSBoundParameters.ContainsKey("Raw")) { try { return $($response | ConvertTo-Json -Depth 100 -ErrorAction Stop -WarningAction SilentlyContinue) } catch { Write-Error -Exception $_.Exception -Category InvalidResult -ErrorAction Stop } } else { try { return $response } catch { Write-Error -Exception $_.Exception -Category InvalidResult -ErrorAction Stop } } } } } |