-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathNew-ApiRequest.ps1
121 lines (99 loc) · 2.45 KB
/
New-ApiRequest.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
function New-ApiRequest
{
<#
.SYNOPSIS
Function will query data from an URL API.
.DESCRIPTION
Function is intended as a wrapper around PowerShell built-in Invoke-RestMethod cmdlet allowing user to quickly generate web requests to APIs requiring OAuth2 authentication.
.PARAMETER ApiKey
A string representing the API key to be used.
.PARAMETER ApiSecret
A string representing the API key secret.
.PARAMETER ApiUrl
A string representing the API endpoint URL
.PARAMETER GrantType
A string representing the Grant Type supported by the API.
If not specified it will default to client_credentials.
.PARAMETER ContentType
A string representing the content type to send as part of the request in case request needs to be crafted with a special ContentType.
.PARAMETER Method
A string representing the method to be used in the web request.
If not specified it will default to GET.
.PARAMETER Headers
A string representing custom headers to send as part of the webrequest.
.EXAMPLE
PS C:\> New-ApiRequest -ApiKey 'Value1' -ApiUrl 'Value2' -ApiSecret 'MySecret'
.NOTES
Additional information about the function.
#>
[CmdletBinding()]
[OutputType([pscustomobject])]
param
(
[Parameter(Mandatory = $true)]
[string]
$ApiKey,
[string]
$ApiSecret,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]
$ApiUrl,
[ValidateNotNullOrEmpty()]
[string]
$GrantType = 'client_credentials',
[ValidateNotNullOrEmpty()]
[string]
$ContentType,
[ValidateNotNullOrEmpty()]
[ValidateSet('GET', 'POST', IgnoreCase = $true)]
[string]
$Method = 'GET',
[ValidateNotNullOrEmpty()]
[string]
$Headers
)
Process
{
# Generate request post data
[hashtable]$requestBody = @{
'client_id' = $ApiKey;
'grant_type' = $GrantType
}
switch ($PSBoundParameters.Keys)
{
'ContentType'
{
$requestBody.Add('ContentType', $ContentType)
break
}
'ApiSecret'
{
$requestBody.Add('client_secret', $ApiSecret)
break
}
}
# Define splat command
$paramInvokeWebRequest = @{
Uri = $ApiUrl
Body = $requestBody
}
# Get passed parameters
switch ($PSBoundParameters.Keys)
{
'Headers'
{
# Add custom header
$paramInvokeWebRequest.Add('Headers', $Headers)
break
}
'Method'
{
# Use custom method
$paramInvokeWebRequest.Add('Method', $Method)
break
}
}
return Invoke-RestMethod @paramInvokeWebRequest
}
}