Here is a quick guide on how to get started with the VSTS REST API.

This post will use a C# REST client implementation, but you can write this in almost every language. What is important is that you can create a basic authorisation header and set the content header of your transmission to “application/json”.

To talk to the VSTS REST API, we need to first get a personal access token. This allows us to authenticate with VSTS with a one-time password that expires after a set amount of time.

Follow the instructions here to create one:

Once we have got the access token, we can create our REST client.

Step 1: First we need to create the client object. You will notice that I passed the personal access token in plain text here, which is against the best practice. The access token should be treated just like a password. To learn more about what Microsoft recommends regarding the use of secrets and passwords in applications, click the link below:

Step 2: We create the client and set the content type as required by the VSTS REST API.

Step 3: This is where we switch our authentication method to “Basic” which means that the REST API will expect us to use a valid access token. We pass the personal access token here in a formatted string that we convert to bytes. If you are wondering about the format {0:1}, this represents a user name and a password. Because we are using the access token, the username is ignored, we only provide the password. (or token)

Once we have got our client we can run REST calls like so:

using (HttpResponseMessage response = client.GetAsync("https://{account}").Result)
string responseBody = await response.Content.ReadAsStringAsync();

Do not forget to dispose

Both the HttpClient and the HttpResponseMessage are disposable types. You can either wrap them in a “using” statement or dispose of them by calling .Dispose(); on their object reference when you do not need them anymore. This gives the instances a chance to properly destroy any manged resources they might be using.

One thought on “VSTS REST API: Getting started

Comments are closed.