LoginSignup
6
8

More than 5 years have passed since last update.

WebAPIをPowerShellからテストする

Last updated at Posted at 2019-03-09

はじめに

WebAPIを作ってブラウザでテストしていたら、GETはいいけど、POSTのテストで簡単なHTMLフォームを作るのすらめんどくさいと思ったので、PowershellからPOSTしてみました。

参考

以下のURLを参考にWebAPIをSpringBootで作成しました。
SpringBootに入門する為の助走本(随時更新)

大変わかりやすく記載されており、たくさんSpringBootの入門ページを見させていただいた中で一番参考になったと感じております。
執筆ありがとうございます。

Powershellから実行

ここからは、前述の参考URLをもとに、WebAPIが構築されている前提で話を進めさせていただきます。

GET

パラメータの無い、ただのGETは以下です。

ただのGET
invoke-restmethod -uri "http://localhost:8080/api/hello" -method get
SpringBoot!

SpringBoot!と言う文字列が返されました!

GET - パス変数有り

パス変数のあるGETは以下です。

パス変数のあるGET-1
invoke-restmethod -uri "http://localhost:8080/api/test/xxx" -method get
受け取ったパラメータ: xxx

xxxがパラメータとして渡されました。
invoke-restmethodのuriオプションのパラメータのうち、xxxの個所を変えると、WebAPIに渡すパラメータを変更することができます。

パス変数のあるGET-2
invoke-restmethod -uri "http://localhost:8080/api/test/検索したい文字列" -method get
受け取ったパラメータ: 検索したい文字列

POST

POSTでパラメータを送る例は以下です。

POST-1
$data = @{param = 10}
invoke-restmethod -uri "http://localhost:8080/api/test/" -method post -body $data
受け取ったパラメータ: 10

一行目の、@{param = 10} はPowershellのHashtableオブジェクトです。
ユーザー情報のようなオブジェクトを渡す場合、以下のようになります。

hashtable
$data = @{name = "wakoit"; phone_number = "000-0000-0000"

WebAPI側でparam変数を待っているので、合わせてあげないと例外が発生しました。

POST-2
$data = @{name = "wakoit"; phone_number = "000-0000-0000" }
invoke-restmethod -uri "http://localhost:8080/api/test/" -method post -body $data
invoke-restmethod : リモート サーバーがエラーを返しました: (400) 要求が不適切です
発生場所 :1 文字:1
+ invoke-restmethod -uri "http://localhost:8080/api/test/" -method post ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod]WebExce
    ption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

この場合、WebAPI側で受け取るように改修する必要があります。

POST-3
$data = @{param = "wakoit"; phone_number = "000-0000-0000" }
invoke-restmethod -uri "http://localhost:8080/api/test/" -method post -body $data
受け取ったパラメータ: wakoit

paramにすれば、うまくいきますが、2つ目のphone_numberパラメータは出力していないので無視されています。

まとめ

Invoke-RestMethod素敵!

以上です。

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8