First, a poem about APIs:

API, API,
you are the apple of my eye.
I used to be dejected,
But you made my life connected.
Endpoints, Methods, and Calls,
Not just one, I love you all.
Why do something manually,
When I can do it automagically?
API, API…
You a dime.

\\\Just a Jiffy

Contrary to popular belief, other than that riveting and deeply symbolic last line, I totally did not write this masterpiece in less than 2 minutes on a Monday.

On topic, when it comes to working with APIs we have tons of options and different tools and ways we can go about testing. You may fire up something like Postman or use PowerShell, Python, or your language of choice. If I’m targeting a system/endpoint that I’m going to use multiple methods or frequent calls, I like to make my life a little easier in PowerShell. My line of work usually gravitates around Active Directory or some other Microsoft product so I stick close to PowerShell.

In this post, I’m going to show you how I set up my code to work quickly in my IDE and how you can turn it into a function to quickly test out various APIs without reinventing the wheel over and over again.

\\\First and foremost

Fire up the shell of powah and let’s get started. Actually, if you haven’t already, it’s a fantastic idea to test out your API first and make sure the basic functionality works with something like Postman or Insomnia. Once that’s validated, we can move on to adding an additional layer of possible screwups in PowerShell. I’m speaking about myself, of course. You are in no way a screwup and you never make mistakes. You’re just reading this for fun, aren’t you? You sick, twisted, perfect human you.

For the rest of us, now that we know what the URI should look like and we know the authorization requirements, let’s move on to PowerShell. If you closed PowerShell one paragraph ago after testing the API, slap yourself and then fire up the shell of powah once more.

I like to break it down in variables so I can easily pretend they are LEGOs and build new creations by moving pieces around. Although it can vary based on the specific API, the basic structure looks like this:

$BaseURL + $Endpoint + $Parameters

This way I can quickly change the methods and/or parameters without redefining everything again. For our example, I’ll be utilizing the API available with my Goodreads account.

\\\Strategic Setup

If you have a Goodreads account and want to follow along with this specific API, you can request your key here. This will give you a key and a secret. Shhhh! Don’t tell me. And no, it’s not the deoderant. For our test, we’ll only need the key since we’re reading and not writing. Lord knows we can’t do both.

One of the endpoints is to query an author by name and get his/her ID, which we can then use to get the books by that author. Altogether the URI looks like this:

https://www.goodreads.com/api/author_url/H G Wells/?key=XXXXXXXXXXXXXXX

We’ll need to define the following parts:

Side Note: We’re only using the GET method here, but you could also define the $Method as a variable so you can quickly differentiate between methods.

To start out our script, let’s define the variables common to all of our endpoints:

$Key = 'XXXXXXXXXXXXXXX'
$KeyString = "key=$Key"
$BaseURL = 'https://www.goodreads.com/'

\\\Scintillating Switch

Since we want to be able to quickly test multiple endpoints, all of these will share the same $BaseURL, $Key, and $KeyString. What we usually change is the $Endpoint and $Criteria. To easily make the magic mesermize monsieur, we can utilize a switch statement in PowerShell. If you haven’t used switch statements before, they’re like if statements on roids but without the negative publicity and frowns from the athletic community.

Two roads diverged in a yellow wood, and our switch statement is going to allow us to take whichever road we flippin’ want to take. We want to define the $Endpoint and $Criteria variables and then have everything else formated automatically for us. In the snippet below, we’re switching the $Endpoint variable, which then determines how our $EndpointString is defined, and ultimately determines our $URI string.

For demonstration purposes, I’ve added 4 endpoints to my switch statement. And for my sanity, I’ve commented out and example of what the URI should end up looking like.

Switch Statement
Switch ($Endpoint){
    'UserInfo'{
        $EndpointString = "user/show/$Criteria.xml?$KeyString"
        $URI = $BaseURL + $EndpointString
        #https://www.goodreads.com/user/show/8898794.xml?key=XXXXXXXXXXXXXXXXX
    }
    'Author'{
        #Search author by name
        $EndpointString = 'api/author_url/'
        $URI = $BaseURL + $EndpointString + $Criteria + "/?$KeyString"
        #https://www.goodreads.com/api/author_url/Orson%20Scott%20Card?key=XXXXXXXXXXXXXXXXX
    }
    'BooksByAuthor'{
        #Books by Author using Author's ID
        $EndpointString = "author/list/$Criteria" + "?format=xml&$KeyString"
        $URI = $BaseURL + $EndpointString
        #https://www.goodreads.com/author/list/18541?format=xml&key=XXXXXXXXXXXXXXX
    }
    'BookInfo'{
        #Book Info using Book's ID
        $EndpointString = "book/show/$Criteria.xml?$KeyString"
        $URI = $BaseURL + $EndpointString
        #https://www.goodreads.com/book/show/50.xml?key=XXXXXXXXXXXXXXXXXXXX
    }
}

\\\facile finale

After the $URI is defined, all we have to do is use it in the Invoke-RestMethod cmdlet and we can cry, “havoc!” and let slip the dogs of war. Goodreads responds with an XML response and we can get our info in the “GoodreadsResponse” XML element. Each endpoint is slightly different, but we can store it in a variable and parse it until we’re pale in the face. This last line looks like this:

$Results = (Invoke-RestMethod -Uri $URI -Method Get).GoodreadsResponse
Cowards die many times before their deaths, so let’s be bold and put all of this together. Here’s what we have:
Final Script
########################################
#Define the endpoint and criteria below:
$Endpoint = 'BookInfo'
$Criteria = '8909'
########################################
$Key = 'XXXXXXXXXXXXXXXXXX'
$KeyString = "key=$Key"
$BaseURL = 'https://www.goodreads.com/'
Switch ($Endpoint){
    'UserInfo'{
        $EndpointString = "user/show/$Criteria.xml?$KeyString"
        $URI = $BaseURL + $EndpointString
        #https://www.goodreads.com/user/show/8898794.xml?key=XXXXXXXXXXXXXX
    }
    'Author'{
        #Search author by name
        $EndpointString = 'api/author_url/'
        $URI = $BaseURL + $EndpointString + $Criteria + "/?$KeyString"
        #https://www.goodreads.com/api/author_url/Orson%20Scott%20Card?key=XXXXXXXXXXXXX
    }
    'BooksByAuthor'{
        #Books by Author using Author's ID
        $EndpointString = "author/list/$Criteria" + "?format=xml&$KeyString"
        $URI = $BaseURL + $EndpointString
        #https://www.goodreads.com/author/list/18541?format=xml&key=XXXXXXXXXXXXXXX
    }
    'BookInfo'{
        #Book Info using Book's ID
        $EndpointString = "book/show/$Criteria.xml?$KeyString"
        $URI = $BaseURL + $EndpointString
        #https://www.goodreads.com/book/show/50.xml?key=XXXXXXXXXXXXXXXX
    }
}
$Results = (Invoke-RestMethod -Uri $URI -Method Get).GoodreadsResponse

I like this a lot, but still I rise. Although this is a great way to manually edit a few variables to test different APIs, we can take it up a notch by turning this into a function so we can easily make this a one liner and pipe to and from this gato. Check out Part 2 of Quickly Testing APIs in PowerShell to see some cheap magic tricks!

OTHER POSTS YOU WANT TO READ

Index Scripts for Windows Search

So you just finished writing some code and you go to save your file. You summarize all of the important aspects this section of code contains into a nice, easy-to-read file name that your future self will immediately recognize. Fast forward to the future where you...

Array vs ArrayList (PowerShell)

For some tasks in life, being precise is a necessity. But most of us get away with rounding, paraphrasing, and hitting in the general vicinity most of the time. Depending on your personality, you may be one who strives for perfection and strains on every miniscule...

Spice Up HTML Emails with PowerShell – Part III

So far in this series we've fumbled our way around the kitchen and tried to wing it when sending HTML emails with PowerShell. It was clunky to say the least. We then went through our spice rack and built an HTML template, highlighting the nuances of each spicy element...

Spice up HTML Emails with PowerShell – Part II

In Part I of our scrumptious concoction we put our script into the oven to let it bake. But we forgot to add our secret sauce that's sure to leave our recipients drooling, which is clearly our goal. In this post we'll continue to spice up HTML emails with PowerShell...

Spice Up HTML Emails with PowerShell – Part I

I live in the South, specifically in God's country AKA TEXAS BABAY! There's plenty of amazing things about Texas and definitely some reasons to loathe being from Houston, but it's hard to knock our food. I mean, is there really even a debate between Whataburger vs...
%d bloggers like this: