How to call API inside function. this is my url https://www.gov.uk/bank-holidays.json. I am new for powershell can you help me to do this.
function Holiday {
$list = Invoke-RestMethod -Method Get -Uri https://www.gov.uk/bank-holidays.json
Write-Host "$list"
}
but i am unable to list . can u please help me on that
Invoke-RestMethod
automatically parses the API's JSON response into an object [graph] - a nested [pscustomobject]
instance or an array thereof (in a manner of speaking, Invoke-RestMethod
has ConvertFrom-Json
built in).
While very convenient for subsequent OO processing, the resulting objects' display representation isn't very helpful:
To quickly visualize the result, you can simply convert back to JSON, using ConvertTo-Json
:
function Get-Holiday {
# Call the API, which returns JSON that is parsed into a [pscustomobject]
# graph, and return (output) the result.
Invoke-RestMethod -Method Get -Uri https://www.gov.uk/bank-holidays.json
}
$list = Get-Holiday
# Visualize the object for display by converting it back to JSON.
$list | ConvertTo-Json -Depth 3
-Depth 3
explicitly - see this post for background information.An alternative visualization can be achieved by piping to Format-Custom
:
Format-Custom
's default depth is 5 (compared to ConvertTo-Json
's 2), so you will often get away without a -Depth
argument.$FormatEnumerationLimit
preference variable to ensure that all elements of a collection are visualized; by default, only 4 are, and omitted elements are represented as …
.# Assumes that $list was obtained as above.
$list | Format-Custom
Output (showing just the first object; note the …
indicating that the collection contained in the .events
property has additional elements that were omitted):
class PSCustomObject
{
england-and-wales =
class PSCustomObject
{
division = england-and-wales
events =
[
class PSCustomObject
{
title = New Year’s Day
date = 2018-01-01
notes =
bunting = True
}
class PSCustomObject
{
title = Good Friday
date = 2018-03-30
notes =
bunting = False
}
class PSCustomObject
{
title = Easter Monday
date = 2018-04-02
notes =
bunting = True
}
class PSCustomObject
{
title = Early May bank holiday
date = 2018-05-07
notes =
bunting = True
}
…
]
}
With respect to processing, here's an example that accesses the first entry for England and Wales:
$list.'england-and-wales'.events[0]
The above yields:
title date notes bunting
----- ---- ----- -------
New Year’s Day 2015-01-01 True