【curlコマンド】WindowsでPOSTリクエストの-dの値の記載方法

cmd

スポンサーリンク

WindowsのコマンドプロンプトでcurlコマンドでAPIリクエストを作成する際に、-dの記載方法で躓いたので、注意点を記載します。

正しい記載方法

curl -X "POST" "https://localhost:7105/SampleApi" -H "Content-Type: application/json" -d "{\"name\": \"田中\",\"tel\": \"090\"}"

上記のように-dに限らず、各オプションの値はシングルクオーテーションではなく、ダブルクオーテーションで囲む

-dにJSON形式で記載する際は、外側はダブルクオーテーションで囲み、内部のダブルクオーテーションは「\"」でエスケープして記載する。(上記curlコマンドの赤字部分)

誤った記載方法

curl -X "POST" "https://localhost:7105/SampleApi" -H "Content-Type: application/json" -d "{"name": "田中","tel": "090"}"

上記のように-dのJSONの内部のダブルクオーテーションをエスケープせずに記載すると、以下の赤字部分のようなエラーになる。

C:\Users\totot>curl -X "POST" "https://localhost:7105/SampleApi" -H "Content-Type: application/json" -d "{"name": "田中","tel": "090"}"
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"errors":{"$":["'n' is an invalid start of a property name. Expected a '\"'. Path: $ | LineNumber: 0 | BytePositionInLine: 1."],"apiRequest":["The apiRequest field is required."]},"traceId":"00-42d95bdb4007c16c8fa85978b82387eb-70e54166c2651086-00"}

cmd

Posted by ton