PowerShell RestFul API (Invoke-RestMethod)

2022-01-08

筆記如何使用 PowerShell 進行 Restful API 的 GET, PATCH, POST, DELETE, PUT。

logo

API Server

本次的使用上搭配 json-server 作為呼叫的 Uri 位址。

{
  "Pokemons": [
    {
      "Pno": 1,
      "Name": "Bulbasaur",
      "Name_CT": "妙蛙種子",
      "HP": 45,
      "Atk": 49,
      "Def": 49,
      "SpAtk": 65,
      "SpDef": 65,
      "Speed": 45,
      "Type": ["Grass", "Poison"]
    },
    { ... }
}
json-server --watch pokemon.json --port 8888 -i Pno

PowerShell

Get

$uri = "http://localhost:8888/Pokemons"
$p = Invoke-RestMethod $uri/16

回應的結果為會自動轉為物件

Pno     : 16
Name    : Pidgey
Name_CT : 波波
HP      : 40
Atk     : 45
Def     : 40
SpAtk   : 35
SpDef   : 35
Speed   : 56
Type    : {Normal, Flying}

物件可以使用 ConvertTo-Json 的方式轉為 Json。

$p | ConvertTo-Json
{
  "Pno":  16,
  "Name":  "Pidgey",
  "Name_CT":  "波波",
  "HP":  40,
  "Atk":  45,
  "Def":  40,
  "SpAtk":  35,
  "SpDef":  35,
  "Speed":  56,
  "Type":  ["Normal", "Flying"]
}

Delete

Invoke-RestMethod $uri/1 -Method delete

PATCH

Invoke-RestMethod $uri/2 -Method Patch `
  -Body ($Body | ConvertTo-Json) `
  -ContentType "application/json"
Pno     : 2
Name    : Ivysaur
Name_CT : 妙蛙草
HP      : 100
Atk     : 100
Def     : 63
SpAtk   : 80
SpDef   : 80
Speed   : 60
Type    : {Grass, Poison}

POST

Post Method 會建立新的資源項目。

$golduck = Invoke-RestMethod $uri/55
$golduck.Pno = 152
$golduck.Name = "GoldDark"

Invoke-RestMethod $uri -Method POST `
  -Body ($goldduck | ConvertTo-Json) `
  -ContentType "application/json"

PUT

Put Method 會取代現有資源項目。

$pikachu = Invoke-RestMethod $uri/25
$pikachu.Name = "Pikaju"

Invoke-RestMethod $uri/25 -Method PUT `
  -Body ($pikachu | ConvertTo-Json) `
  -ContentType "application/json"

查詢應用

$ps = Invoke-RestMethod $uri

篩選資源

 $ps | ? {$_.HP -ge 100 -and $_.Atk -ge 50} | select name, name_ct, hp, atk
Name       Name_CT   HP Atk
----       -------   -- ---
Wigglytuff 胖可丁   140  70
Muk        臭臭泥   105 105
Rhydon     鑽角犀獸 105 130
Kangaskhan 袋獸     105  95
Lapras     拉普拉斯 130  85
Vaporeon   水伊布   130  65
Snorlax    卡比獸   160 110
Mewtwo     超夢     106 110
Mew        夢幻     100 100

彙總欄位

$ps | `
  select name, name_ct, `
  @{name="sum"; expression = {$_.hp + $_.atk + $_.def + $_.dex + $_.spatk + $_.spdef}} `
  | sort sum -Descending `
  | select -First 10
Name      Name_CT  sum
----      -------  ---
Mewtwo    超夢     550
Dragonite 快龍     520
Snorlax   卡比獸   510
Mew       夢幻     500
Articuno  急凍鳥   495
Moltres   火焰鳥   490
Zapdos    閃電鳥   480
Lapras    拉普拉斯 475
Exeggutor 椰蛋樹   465
Slowbro   呆殼獸   460

欄位彙總計算

$ps | measure -Property "Hp" -Max -Minimum -Average
Count    : 151
Average  : 64.2119205298013
Sum      :
Maximum  : 250
Minimum  : 10
Property : HP

相關連結

PowerShell 使用者不能錯過的 5 個技巧

Powershell 使用物件與資料結構 (Array, Hash)

PowerShell 常用指令筆記

參考資料

Calling a REST API from PowerShell