Office 365 REST API calls from a .net console application

Rahatur picture Rahatur · Jan 11, 2016 · Viewed 14.1k times · Source

Please note that this question is not regarding generic REST service calling. Its about specific Office 365 REST service API.

To be specific I need to utilize the 'Contact' API here: https://msdn.microsoft.com/office/office365/APi/contacts-rest-operations#UsingtheContactsRESTAPI

I was wondering how the Office 365 REST services can be utilized in a Console application. There are tools to deal with the APIs from Web, mobile and windows store apps. But I found no resource for console application.

I have the application created on the application registration portal here: https://apps.dev.microsoft.com

So I already have the Application Id, Application Secrets, Platforms Mobile application (Client Id, Redirect URI)

I think I will need the authentication token (I have the Username, password). And use that to call the REST services.

Answer

Vadim Gremyachev picture Vadim Gremyachev · Jul 27, 2016

Currently for Office 365 Mail, Calendar, and Contacts APIs two versions are supported: v1 and v2

About REST API v2

The Office 365 API services use Azure Active Directory (Azure AD) to provide secure authentication and authorization to users' Office 365 data. Azure AD implements authorization flows according to the OAuth 2.0 protocol.

To allow your application access to the Office 365 APIs, you need to register your application with Azure AD.


In case of API v1 version, since it supports Basic authentication, the following example demonstrates how to read contacts in console app using user credentials:

Example

class Program
{
    static void Main(string[] args)
    {

        ReadContacts().Wait();
    }

    private static async Task ReadContacts()
    {
        var handler = new HttpClientHandler();
        handler.Credentials = new NetworkCredential()
        {
            UserName = ConfigurationManager.AppSettings["UserName"],
            Password = ConfigurationManager.AppSettings["Password"]
        };

        using (var client = new HttpClient(handler))
        {
            var url = "https://outlook.office365.com/api/v1.0/me/contacts";
            var result = await client.GetStringAsync(url);

            var data = JObject.Parse(result);

            foreach (var item in data["value"])
            {
                Console.WriteLine(item["DisplayName"]);
            }
        }
    }
}