Welcome to part 2 of our series on API development! In this article, we will build on our basic introduction to working with REST APIs, and discuss a few more of the basics of how to interact with a REST API. The code samples will be in PowerShell, but the concepts apply broadly.
Authentication
how to authenticate with a REST API. Nearly all APIs you’ll interact with require some sort of authentication in order to perform operations.
There are many ways to authenticate with an API, but two of the most common (and easiest to work with) methods are Basic Authentication and Header Key Authentication.
Basic Authentication involves sending a base64-encoded representation of the username and password with each API request, and Header Header Key Authentication involves sending a unique key with each API request in the header of the HTTP request. Because both require sending a secret directly over the wire, they should only ever be used over HTTPS.
Let’s take a look at how to implement these authentication methods in PowerShell.
Basic Authentication:
$uri = "https://dummyapi.com/users" $username = "myusername" #sometimes this will be a public key instead $password = "mypassword" #sometimes this will be a private key instead $headers = New-Object"System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add("Authorization", "Basic "+ [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($username+":"+$password))) $response = Invoke-RestMethod-Uri$uri -Method Get -Headers $headers
In this example, we are sending a GET request to the API endpoint at https://dummyapi.com/users using Basic Authentication. We create a dictionary of headers, and add an “Authorization” header with the value “Basic ” followed by the base64-encoded username and password.
In most cases with real-world APIs, you’ll generate a public/private key that can be used for basic authentication. This improves security significantly since you’re not sending your user credentials over the wire, and the public/private key can be revoked separately from changing your user credentials. In many cases, distinct application credentials can be issued to the public/private key pair.
Basic Authentication always looks like sending an “Authorization” header type, with a value of “Basic <base64-encoded username:password string>”. (Sometimes, there are additional parameters like a database or tenant name at the beginning of the string, or instead of a username it may be public/private keypair, like this: “tenant+publickey:privatekey”).
Header Key Authentication:
$uri = "https://dummyapi.com/users" $key = "myapikey" $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add("X-Api-Key", $key) $response = Invoke-RestMethod -Uri $uri-Method Get -Headers $headers
In this example, we are sending a GET request to the API endpoint at https://dummyapi.com/users using Header Key Authentication. We create a dictionary of headers, and add an “X-Api-Key” header with the value of our API key. The header name will typically be “X-Api-Key” and the key value is typically generated once in the admin backend of the application. Well-secured web apps let you create multiple API keys so that individual integrations can be added and revoked as needed.
A third common authentication scheme for REST APIs that we won’t cover here is using token-based (“Bearer”) authentication. Typically that looks like an initial authentication using Basic or header auth (for instance to a “/login” endpoint) that generates a time-limited authentication token. That token is then used for subsequent requests until it expires. Your code would need to check validity and then refresh the token or request a new one before each request. There are a number of other authentication schemes for APIs. Other authentication schemes that are less common for REST APIs include OAuth, OpenID, and Cookie-based authentication.
Parameters
In addition to authentication, you may also need to add parameters to your API requests. Parameters can be used to send data to the server, but most commonly are added to a GET request to specify more details on the data you’re requesting from the API. This can include parameters for filtering, sorting, and boolean checks (true/false).
Here is an example of using parameters with a GET request. This request would be expected to return any users named John, age 30:
Method 1: using URL Parameters
$uri = "https://dummyapi.com/users" $key= "myapikey" $name "John" $age = 30 $headers= New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add("X-Api-Key", $key) $response = Invoke-RestMethod -Uri "$uri?name=$name&age=$age" -Method Get -Headers $headers $response
Method 2: using the request body
$uri = "https://dummyapi.com/users" $key = "myapikey" $parameters = @{ name = "John" age = 30 } | ConvertTo-Json # I can do this all in one line! $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add("X-Api-Key", $key) $response = Invoke-RestMethod -Uri $uri-Method Get -Headers $headers -Body $parameters -ContentType application/json
Pagination
$pageNumber = 1 $results = @() $uri = "https://dummyapi.com/users" do { $result = Invoke-RestMethod -Uri "$uri/$page_no=$pageNumber -Method Get -Headers $headers $results += $result $pageNumber++ } while ($result)