Making better REST calls – Powershell

As of late my life solely exists to make things occur automagically. Most end points these days are REST based, which is a great thing. REST is super simple to use but many make a few simple mistakes when writing their calls. Hopefully I can show off a few tricks to help you out in the future.

Alright so lets walk through some of this. First we setup a private hashtable, I like to do this in my functions to track errors as well as returning only a single named var with sub vars or sub objects. We build our URI as well as our http headers used for auth. Next we actually attempt to call our rest method in a try catch, if it fails we catch everything and set the exception to our private return var as well as a status code. We then output a few properties within the exception, the most important one is status code, notice how at first its a string but if we cast it as an int it becomes the numerical http status code, this is very helpful. You now have all the pieces needed to recover or if it was successful move on to the next task.

Note how I do not do any form of logic within the catch block, I dislike nested try catches and I urge you to as well. They become hard to read and harder to troubleshoot.

Ok so we have our status code, what do we do with it? Well if we get a 401 maybe we want to try and re connect and re execute to recover? Or maybe we just want to log the error? Or maybe we have a fallback method we can use to get a similar outcome? It really doesnt matter what you want to do but now you have the options to do it. As I said before I like to remove any logic in the catch blocks, you can add another try catch within your if scopes to recover. This makes your code far easier to follow and maintain in the future.

A full list of http status codes and their meanings can be found here:

I hope that helps you with any future REST calls!

1 comment… add one

Leave a Comment