When I first tried to learn how to use the REST API for Team Services I really struggled so I thought I would give a simple example on how to get started using the REST API with PowerShell and Node.js.
To follow along you will need the following:
Optional items:
The part that was not clear to me is that once you have the Personal Access Token you do not have to worry about a user name. The second thing that was very unclear was that the Personal Access Token had to be 64 bit Encoded to be passed in the header of your request.
Postman
Before I jumped into trying to write code I used a tool called Postman to call the APIs and review the responses.
- Start Postman
- Set the verb to GET
- Enter the following URL replacing {Your Team Services Account} with your Team Services account name
https://{Your Team Services Account}.visualstudio.com/defaultcollection/_apis/projects?api-version=1.0 - Select Basic for Authorization type
Field Name | Value |
Username | {Leave Blank} |
Password | {Your Personal Access Token} |
- Click Send
Postman will send the request to Team Services and return a JSON object with a collection of your Team Projects. One great feature of Postman is the ability for it to generate code in many different languages for you.
Now that we know we have a good Personal Access Token we can move to writing code. Below you will find code in both PowerShell and Node.js with techniques on encoding your Personal Access Token for use in the REST API calls.
PowerShell
This PowerShell script will work on Mac, Linux and PC.
$version = '1.0'
$account = '{Your Team Services Account}'
$resource = '/projects'
$collection = '/DefaultCollection'
$instance = "$account.visualstudio.com"
$pat = '{Your Personal Access Token}'
$encodedPat = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$pat"))
# Build the url to list the projects
$listurl = 'https://' + $instance + $collection + '/_apis' + $resource + '?api-version=' + $version
# Call the REST API
$resp = Invoke-RestMethod -Uri $listurl -Headers @{Authorization = "Basic $encodedPat"}
Write-Output $resp.value
Node.js
Make sure you use npm to install the request package using the following command before trying to run the code below.
npm install request
var request = require("request");
var encodedPat = encodePat('{Your Personal Access Token}');
var options = {
method: 'GET',
headers: { 'cache-control': 'no-cache', 'authorization': `Basic ${encodedPat}` },
url: 'https://{Your Team Services Account}.visualstudio.com/defaultcollection/_apis/projects',
qs: { 'api-version': '1.0' }
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
function encodePat(pat) {
var b = new Buffer(':' + pat);
var s = b.toString('base64');
return s;
}