Exercise 3: A POST Request with Auth and Real Error Reading — Possible Solution ==================================================================== THE CODE ------------------------------ $body = @{ name = "New Item"; price = 19.99 } | ConvertTo-Json $headers = @{ Authorization = "Bearer $token" } try { Invoke-RestMethod -Uri "https://api.example.com/items" -Method Post -Body $body -ContentType "application/json" -Headers $headers } catch { "HTTP failure: $($_.Exception.Message)" "API said: $($_.ErrorDetails.Message)" } WHY EACH PIECE IS THERE ------------------------------ $body is built from a hashtable and converted with ConvertTo-Json, per this chapter's own POST example, reusing Fundamentals 8's own JSON-conversion material. $headers carries the Bearer token in the Authorization header, matching this chapter's own authentication pattern exactly. -Method Post, -Body $body, and -ContentType "application/json" together send the JSON body as a real POST request, and -Headers $headers attaches the authentication. The try/catch needs no -ErrorAction Stop, per this chapter's own explanation that HTTP errors from Invoke-RestMethod are terminating by default. Inside catch, $_.Exception.Message gives the generic HTTP failure description, while $_.ErrorDetails.Message - per this chapter - surfaces the actual response body text from the API itself, which is usually the genuinely useful explanation of what went wrong. WHY THIS WORKS AS AN ANSWER ------------------------------ It provides a correct, complete POST request combining a JSON body, a Bearer token header, and try/catch error handling, and correctly uses both $_.Exception.Message and the more useful $_.ErrorDetails.Message inside the catch block, matching this chapter's own recommended error-reading pattern.