Working with REST APIs in PowerShell

REST APIs are getting more and more common these days. It is important to learn them to be successful in the DevOps field. In previous blog post, we have used Invoke-WebRequest cmdlet to access the data available to an anonymous user.

PowerShell makes working with rest API’s easy. Starting with PowerShell v3, the cmdlets Invoke-RestMethod and Invoke-WebRequest were introduced. The difference between the two is quite small, Invoke-RestMethod simply being a slightly more convenient wrapper around Invoke-WebRequest as it only returns the content, omitting the headers.

This cmdlet is located in the Microsoft.PowerShell.Utility module:

Invoke-RestMethod cmdlet
Invoke-RestMethod cmdlet

There is only one cmdlet to do all kinds of REST based request like GET, POST which all are available as the parameters:

Invoke-RestMethod cmdlet available parameters

The simplest call you can make is to call the cmdlet by just providing the URL without providing any parameters. This will default to a GET request, and any unsupplied optional parameters are omitted from the request. For example, this GET request won’t have a content type. For example, let’s consider a sample request as below:

$content = Invoke-RestMethod https://blogs.msdn.microsoft.com/feed/

The value returned will be automatically parsed depending on the content type of the response. We can then simply process the request using normal methods:

$content | ft title, pubdate

Processing data returned by the request

Most of the REST APIs would require some kind of authentication too. There are various authentication methods available. The most basic one is to use basic authentication. The other would go for more secure one like OAuth, etc. Some would prefer the key based authentication.

Below example uses a key based authentication to retrieve the statistics of a Ed Sheeran’s video from YouTube (Ed Sheeran – Shape of You [Official Video]):

Getting data using key based authentication

In a web browser, it should return this data:

{
 "kind": "youtube#videoListResponse",
 "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/ivgGCjQWvXKptfE2B6qQtaImc04\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#video",
   "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/p3eA6yNYF4_lSmhb3ufhlT2uheg\"",
   "id": "JGwWNGJdvx8",
   "snippet": {
    "publishedAt": "2017-01-30T10:57:50.000Z",
    "channelId": "UC0C-w0YjGpqDXGB8IHb662A",
    "title": "Ed Sheeran - Shape of You [Official Video]",
    "description": "Stream or Download Shape Of You: https://atlanti.cr/2singles\n÷. Out Now: https://atlanti.cr/yt-album\nSubscribe to Ed's channel: http://bit.ly/SubscribeToEdSheeran\n\nFollow Ed on...\nFacebook: http://www.facebook.com/EdSheeranMusic\nTwitter: http://twitter.com/edsheeran\nInstagram: http://instagram.com/teddysphotos\nOfficial Website: http://edsheeran.com\n\nDirector|DOP: Jason Koenig\nProducer: Honna Kimmerer\nProduction company: Anonymous Content\nExec Producer: Nina Soriano\n\nCinematography: Johnny Valencia, Ryan Haug \nEdited by: Johnny Valencia, Jason Koenig\nCommissioner: Dan Curwin\n\nCo-Starring: \nJennie Pegouskie\nYama\n\n-- | LYRICS |--\n\nThe club isn’t the best place to find a lover\nSo the bar is where I go \nMe and my friends at the table doing shots drinking fast and then we talk slow\nyou come over and start up a conversation with just me and trust me I’ll give it a chance now\nTake my hand stop, put van the man on the jukebox and then we start to dance\nAnd now I’m singing like\n\nGirl you know I want your love\nYour love was handmade for somebody like me\nCome on now follow my lead\nI may be crazy don’t mind me \nSay boy let’s not talk too much \nGrab on my waist and put that body on me\nCome on now follow my lead\nCome come on now follow my lead\n\nI’m in love with the shape of you\nWe push and pull like a magnet do\nAlthough my heart is falling too\nI’m in love with your body\nLast night you were in my room \nAnd now my bed sheets smell like you \nEvery day discovering something brand new\nI’m in love with your body\n\nOh I X 4\nI’m in love with your body\nOh I X 4\nI’m in love with your body\nOh I X 4\nI’m in love with your body\nEvery day discovering something brand new\nI’m in love with the shape of you \n\nOne week in we let the story begin\nWe’re going out on our first date\nYou and me are thrifty\nSo go all you can eat \nFill up your bag and I fill up a plate\nWe talk for hours and hours about the sweet and the sour\nAnd how your family’s doing ok\nleave and get in a taxi, then kiss in the backseat\nTell the driver make the radio play\nand I'm singing like\n\nGirl you know I want your love\nYour love was handmade for somebody like me\nCome on now follow my lead \nI may be crazy, don’t mind me\nSay boy let’s not talk too much \nGrab on my waist and put that body on me\nCome on now follow my lead\nCome come on now follow my lead\n\nI’m in love with the shape of you\nWe push and pull like a magnet do\nAlthough my heart is falling too\nI’m in love with your body\nLast night you were in my room \nAnd now my bed sheets smell like you \nEvery day discovering something brand new\n\nWell I’m in love with your body\nOh I x 4 \nI’m in love with your body\nOh I x 4\nI’m in love with your body\nOh I X 4\nI’m in love with your body\nEvery day discovering something brand new\nI’m in love with the shape of you \n\nCome on be my baby come on X 8\n\nI’m in love with the shape of you\nWe push and pull like a magnet do\nAlthough my heart is falling too\nI’m in love with your body\nLast night you were in my room \nAnd now my bed sheets smell like you \nEvery day discovering something brand new\n\nWell I’m in love with your body\nCome on be my baby come on X 6\nEvery day discovering something brand new\nI’m in love with the shape of you",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/JGwWNGJdvx8/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/JGwWNGJdvx8/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/JGwWNGJdvx8/hqdefault.jpg",
      "width": 480,
      "height": 360
     },
     "standard": {
      "url": "https://i.ytimg.com/vi/JGwWNGJdvx8/sddefault.jpg",
      "width": 640,
      "height": 480
     }
    },
    "channelTitle": "Ed Sheeran",
    "tags": [
     "edsheeran",
     "ed sheeran",
     "acoustic",
     "live",
     "cover",
     "official",
     "remix",
     "official video",
     "lyrics",
     "session",
     "Ed",
     "Sheeran",
     "Shape",
     "Of",
     "You",
     "Shape of You",
     "Divide"
    ],
    "categoryId": "10",
    "liveBroadcastContent": "none",
    "defaultLanguage": "en",
    "localized": {
     "title": "Ed Sheeran - Shape of You [Official Video]",
     "description": "Stream or Download Shape Of You: https://atlanti.cr/2singles\n÷. Out Now: https://atlanti.cr/yt-album\nSubscribe to Ed's channel: http://bit.ly/SubscribeToEdSheeran\n\nFollow Ed on...\nFacebook: http://www.facebook.com/EdSheeranMusic\nTwitter: http://twitter.com/edsheeran\nInstagram: http://instagram.com/teddysphotos\nOfficial Website: http://edsheeran.com\n\nDirector|DOP: Jason Koenig\nProducer: Honna Kimmerer\nProduction company: Anonymous Content\nExec Producer: Nina Soriano\n\nCinematography: Johnny Valencia, Ryan Haug \nEdited by: Johnny Valencia, Jason Koenig\nCommissioner: Dan Curwin\n\nCo-Starring: \nJennie Pegouskie\nYama\n\n-- | LYRICS |--\n\nThe club isn’t the best place to find a lover\nSo the bar is where I go \nMe and my friends at the table doing shots drinking fast and then we talk slow\nyou come over and start up a conversation with just me and trust me I’ll give it a chance now\nTake my hand stop, put van the man on the jukebox and then we start to dance\nAnd now I’m singing like\n\nGirl you know I want your love\nYour love was handmade for somebody like me\nCome on now follow my lead\nI may be crazy don’t mind me \nSay boy let’s not talk too much \nGrab on my waist and put that body on me\nCome on now follow my lead\nCome come on now follow my lead\n\nI’m in love with the shape of you\nWe push and pull like a magnet do\nAlthough my heart is falling too\nI’m in love with your body\nLast night you were in my room \nAnd now my bed sheets smell like you \nEvery day discovering something brand new\nI’m in love with your body\n\nOh I X 4\nI’m in love with your body\nOh I X 4\nI’m in love with your body\nOh I X 4\nI’m in love with your body\nEvery day discovering something brand new\nI’m in love with the shape of you \n\nOne week in we let the story begin\nWe’re going out on our first date\nYou and me are thrifty\nSo go all you can eat \nFill up your bag and I fill up a plate\nWe talk for hours and hours about the sweet and the sour\nAnd how your family’s doing ok\nleave and get in a taxi, then kiss in the backseat\nTell the driver make the radio play\nand I'm singing like\n\nGirl you know I want your love\nYour love was handmade for somebody like me\nCome on now follow my lead \nI may be crazy, don’t mind me\nSay boy let’s not talk too much \nGrab on my waist and put that body on me\nCome on now follow my lead\nCome come on now follow my lead\n\nI’m in love with the shape of you\nWe push and pull like a magnet do\nAlthough my heart is falling too\nI’m in love with your body\nLast night you were in my room \nAnd now my bed sheets smell like you \nEvery day discovering something brand new\n\nWell I’m in love with your body\nOh I x 4 \nI’m in love with your body\nOh I x 4\nI’m in love with your body\nOh I X 4\nI’m in love with your body\nEvery day discovering something brand new\nI’m in love with the shape of you \n\nCome on be my baby come on X 8\n\nI’m in love with the shape of you\nWe push and pull like a magnet do\nAlthough my heart is falling too\nI’m in love with your body\nLast night you were in my room \nAnd now my bed sheets smell like you \nEvery day discovering something brand new\n\nWell I’m in love with your body\nCome on be my baby come on X 6\nEvery day discovering something brand new\nI’m in love with the shape of you"
    }
   },
   "contentDetails": {
    "duration": "PT4M24S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "false",
    "licensedContent": true,
    "projection": "rectangular"
   },
   "status": {
    "uploadStatus": "processed",
    "privacyStatus": "public",
    "license": "youtube",
    "embeddable": true,
    "publicStatsViewable": true
   },
   "statistics": {
    "viewCount": "1076593640",
    "likeCount": "7397437",
    "dislikeCount": "305275",
    "favoriteCount": "0",
    "commentCount": "283520"
   }
  }
 ]
}

Once, its processed by the Invoke-RestMethod cmdlet, we can gather details like viewCount, likeCount from PowerShell:

Getting data using key based authentication - 2
Getting data using key based authentication – 2

It’s as simple as this. We’ll get more familiar with other rest methods in upcoming posts.

One thought on “Working with REST APIs in PowerShell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s