RESTful API

GET     POST     PUT     DELETE

PowerShell

and

Ken Maglio  @kenmaglio

STLPSUG

Thank you for joining us!

Monthly Meetings posted on MeetUp

Live Broadcasts and Recordings

 

 

Sponsors

Thank you so much!

Your Organizers:

Mike

Ken

Agenda

  • Introduction to APIs
  • Invoke-RestMethod vs Invoke-WebRequest
  • Authentication
  • JSON
  • Examples
  • Chaining
  • Security

 

Introduction

What is an API?

A structured application that allows computers, not humans, to retrieve data or perform actions easily.

What is REST?

  • Representational State Transfer
  • Not a protocol, but an architecture!
  • Stateless
  • HTTP Verbs
    • GET  POST  PUT  DELETE ...
  • Json

APIs started their life using XML to transfer data between systems. However, XML brings lots of overhead just for the syntax. 

APIs Everywhere!!!

  • Weather
  • Calendar
  • Spell check
  • Train times
  • Confluence
  • Twitter
  • Youtube
  • Jira
  • Slack
  • WordPress
  • Instagram
  • BreweryDB
  • Bing
  • Google Maps
  • URL shortener
  • Meetup
  • eBay
  • Dropbox
  • Buses
  • Amazon
  • Rackspace
  • Facebook
  • Reddit
  • StackOverflow
  • PayPal
  • Spotify
  • Soundcloud
  • IBM Watson
  • Wolfram Alpha
  • New Relic
  • LinkedIn
  • File.io
  • Yelp
  • RoboHash
  • Wikipedia
  • CurrencyLayer
  • Comic Vine
  • Minecraft
  • Pokéapi
  • Postcodes.io
  • Nutritionix
  • Netflix Roulette
  • TFL
  • Ice And Fire
  • Flikr

URI breakdown

Method + Base-Uri + Endpoint + Parameters

http://netflixroulette.net/api/api.php?title=Attack%20on%20titan

Verb Action Example
GET Retrieve Data
POST New Data / Action
DELETE Remove Data
PUT Update Data
Invoke-RestMethod -Uri $uri -Method "POST" -Body $json
Invoke-RestMethod -Uri $uri -Method "GET"
Invoke-RestMethod -Uri $uri -Method "DELETE"
Invoke-RestMethod -Uri $uri -Method "PUT" -Body $json

Invoke Commands

Invoke-WebRequest

Expects HTML as a response

Returns Headers!!!!

Good for querying normal web pages

Invoke-RestMethod

Expects JSON or XML as a response

Only returns data -- No Headers

Great for RESTful APIs  -- go figure!

Authentication

Authorization
Tracking
Throttling

Why???

Basic Auth

Booooooooo

Token-Based

Yeah!!!

Many ways to get API tokens

  • Sign Into Portal - get token
  • OAuth pattern
  • RSA

URL Paramaters ---- YUCK!

Simply chuck the token in as an URL parameter

You better be using HTTPS!!!

Used in some simpler APIs - where token is not securing, just identification

    e.g. Google URL Shortener, Wolfram Alpha, etc.

 

$token = "eaeha0ef9awefawe8awe0f"

$url = "https://api.openweathermap.org/data/2.5/"

# Call API - using Token
$response = Invoke-RestMethod -Uri "$url/weather?q=London&token=$token" -Method Get

Headers

Typically authentication is passed in headers

Most commonly: "X-Auth-Header" or "Authentication"

 

$token = "eaeha0ef9awefawe8awe0f"

# Invoke-RestMessage -Headers takes a hash

$headers = @{"X-Auth-Header" = "$Token"}

$url = "https://api.openweathermap.org/data/2.5/"

# Call API - using Token
$response = Invoke-RestMethod -Uri "$url/weather?q=London" 
                    -Headers $headers -Method Get

JSON

What is JSON?

  • JSON is a “human readable” language-independent data format
  • JSON focuses on a minimalistic syntax
  • Most APIs will return JSON data natively
  • PowerShell 3+ can convert to and from JSON natively.

 

Note: Careful using herestrings. Hard to manipulate and dynamic JSON is rough.

 

(JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language.

ConvertTo / ConvertFrom

ConvertTo / ConvertFrom

Watch Out!!!

Depth default = 3

ConvertTo / ConvertFrom

Other issue!

Automatic conversion of special characters:  <  >  \ ' &

$Json | ConvertTo-Json |  Foreach-object { [System.Text.RegularExpressions.Regex]::Unescape($_) }

XML

JSON

<?xml version="1.0" encoding="ISO-8859-1"?>
<document>
    <patient>
        <firstname>Test</firstname>
        <lastname>Patient</lastname>
    </patient>
    <allergies>
        <allergy>
            <name>Wheat</name>
            <severity>3</severity>
        </allergy>
    </allergies>
</document>
{
    "patient": {
      "firstname": "Test",
      "lastname": "Patient"
    },
    "allergies": {
      "allergy": {
        "name": "Wheat",
        "severity": "3"
      }
    }
}

218 Characters

109 Characters

Examples

Netflix Roulette

With Netflix's official API no longer giving out new keys; they decided to do away with all of that and make this an Open API. You're free to query as much information as you'd like, just mind their bandwidth.

API of Ice and Fire

All the data from the universe of Ice And Fire you've ever wanted!

https://github.com/kenmaglio/presentations

Chaining

Chaining

APIs are great!  We can get the data we need, or update a system.

However, they are the most powerful when you start chaining them together.

In other words, use calls from one API to feed into another API.

 

VM Provisioning

API calls into systems like:

  • VM Ware - VCenter
  • Infoblox - DNS
  • NetApp - Storage
  • Razor - Provisioning
  • Service-Now - Update CMDB

WWT Operations recently completed an overhaul of our VM provisioning process.

 

This process uses API calls into various systems to now automatically provision any quantity of virtual machines.

 

All done by chaining APIs

 

Security

Don't Be Silly

  • Tokens are like passwords, keep them secure.
  • Always use HTTPS when you can.
    • Careful of where / how you use HTTP APIs
  • Don't embed your tokens/keys/passwords in a script
    • Powershell & Windows password store
    • Powershell & Keepass module
    • Store as an encrypted string
      • Secure String -- BE CAREFULL
      • RSA
    • Prompt the user

Thank You!!!

 

Please leave comments or questions!

PowerShell and REST API's

By Ken Maglio

PowerShell and REST API's

Presentation on using REST API's in PowerShell for the STLPSUG on 9/21

  • 1,275