Office as a Platform, Issue No. 5 - Introducing OneNote REST API
In another article, Alexandra Bogdanova talks about using the new OneNote REST API for applications of any type and the example of universal Windows 10 applications. All the articles in the Office as Platform column can always be found at #officeplatform - Vladimir Yunev.OneNote is one of the most popular applications for creating notes, lists, daily routines. To simplify the creation of diary applications, Microsoft released the OneNote API. You can integrate OneNote for working with notes into your application. For developers, the OneNote REST API is available , on the basis of which you can create an application for any platform.

There was already a brief instruction on using the OneNote API on the hub; today I will talk about the features of the OneNote REST API using an example application for Windows 10.
How does the OneNote API work?
The Microsoft OneNote API runs on the globally accessible Microsoft cloud and sends data from your applications to the user's OneDrive client.

Working with the OneNote API in an application consists of three stages:
- Verify user login information and obtain an OAuth token for a Microsoft account in case the user wants to send data to OneNote.
- Sending information and tokens to the API.
- Add data to a notebook on the Internet. Data becomes available in other OneNote clients.
In order to start working with the OneNote API, you need to get a client identifier (clientID). Let's see how to do it.
Getting client identifier (clientID)
Go to the Microsoft Developer Center Development Center and sign in with your Microsoft account. A window will open in which the previously created applications will be shown.
For those who do not have an account: Create a Microsoft account here .

Click Create Application , enter the Application Name and click I Accept.

On the left, select Application Settings , the client ID will appear on the screen . That is what we need.

Next, to use the API in the application, you need to carry out the user authorization process, check his credentials, get a token for executing requests.
User Authentication
When using the OneNote API, an application must request specific permissions when verifying a Microsoft account. For the user, this process is standard - a login and password input form appears, then he is asked to allow the application any activity on his behalf (for example, publish posts or be able to view friends from the social network).
The developer needs to conduct the user authentication process, get a token. We will use the OAuth 2.0 authorization process, for this we need WebAuthenticationBroker .
At the beginning, the client fulfills the authorization request at a specific address, therefore, for a start we need to generate this address. In general terms, it looks as follows:
login.live.com/oauth20_authorize.srf?client_id=CLIENT_ID&scope=SCOPES&response_type=RESPONSE_TYPE&redirect_uri=REDIRECT_URL
The following is a table with the query parameters:
| Parameter | Description | Value |
| CLIENT_ID | Customer id | 00000000 *** |
| SCOPES | Complies with the scope parameter in the OAuth 2.0 specification. | wl.signin% 20wl.basic |
| response_type | The type of data returned in the authorization server response | token |
| REDIRECT_URI | URI to redirect user after authentication | https% 3A% 2F% 2Fwww.tdgdgdgdd.com |
Authorization Request Code (for Windows):
function getToken()
{
//адрес запроса
var startURI = Windows.Foundation.Uri("https://login.live.com/oauth20_authorize.srf?client_id=0000000040*****&scope=wl.signin%20wl.basic&response_type=token&redirect_uri=https%3A%2F%2Fwww.tdgdgdgdd.com");
// REDIRECT_URI
var endURI = Windows.Foundation.Uri("https://www.tdgdgdgdd.com");
// Запуск брокера
return Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
Windows.Security.Authentication.Web.WebAuthenticationOptions.none, startURI, endURI).then(
function onComplete(response) {
return getTokenFromResponse(response.responseData);
},
function onError(error) {
//обработка ошибки
});
}If the request is successful, you will be returned a line in the following form:
https://login.live.com/oauth20_desktop.srf?lc=1033#access_token=******token_type=bearer&expires_in=3600&scope=wl.signin%20wl.basic&user_id = *********
For further requests, we only need what is between access_ token and token_ type , we cut off the lichen:
function getTokenFromResponse(response) {
var startid = response.indexOf("access_token");
var endid = response.indexOf("&", startid + 13);
var token = response.substring(startid + 13, endid);
return token;
}Note the difference in methods for Windows and Windows Phone. For Windows, the authenticateAsync method is used, and for Windows Phone, the authenticateAndContinue method is used. Also consider saving and restoring the application when the authorization window appears.

Excellent! The token is received and now you can make requests.
Sending POST and GET requests
Receive and write data using POST and GET requests.
Currently, the OneNote API allows you to:
- View the list and add new notebooks (Notebooks)
- View the list and add new sections (Sections)
- View the list and add new pages.
- View the contents of pages (Pages) (viewing the contents of pages while in Beta mode)

You can see the format and additional query parameters on the OneNote Development Center website . Also on the site there is an opportunity to choose a language and see an example of a specific request code, as well as an answer option.

In addition to the OneNote Development Center , you can test your request in the apigee.com interactive console .
Work with the apigee interactive console
The console allows you to create a simple REST call to the OneNote API. In order to start working with the console, go to the site .
Click oAuth in the upper left and select OAuth 2 Implicit Grant .

Click the Sign in with OneNote button , then enter your Microsoft credentials.

Confirm that you allow the OneNote API to create pages in OneNote. Click Yes .

Now you can send API requests and create pages in OneNote notebooks that are hosted on OneDrive.
Sending a request using the interactive console
On the left is a gray arrow. Click on it to open a list of possible queries. Then select the query you want to make.
For example, add a new notebook. To do this, select the section Notebooks , POST notebooks .

A page will appear, at the top of which the address of the request will be indicated, just below you can select the data of your request (name of the notebook, the main text of the page, etc.).

Click on the Send button and the request will be sent.

The request body will be displayed on the left side of the screen, and the response from the OneNote API will be displayed on the right. Pay attention to data such as Content-Type and Autorization . They will be needed when you form a request in your application.
Using OneNote API in the Universal App
We learned about the basic steps of working with the OneNote REST API. Now let's look at the capabilities of the OneNote API as an example of a universal HTML and JavaScript application.
The main logic of the application is as follows:
- When the application starts, an authorization window appears, where the user needs to enter a username and password for his account.
- Further, in case of a successful login, a page with a list of viewable notebooks (Notebooks) is loaded.
- Lists of books are loaded in the form of buttons, when you click on each, the corresponding list of sections is loaded. We also come with a list of sections and pages.

Sending a GET request
To load the list, we use the XMLHttpRequest request.
In the open method, we form a GET request. Link - the download address of the notebooks available for viewing, https://www.onenote.com/api/v1.0/notebooks .
Further, in the parameters of the setRequestHeader method, indicate that authorization will occur using the token.
And finally, we process the answer. As an answer, we get a JSON file that needs to be “parsed” for further work. After that, based on the number of available notebooks (sections, pages), buttons are created, in the properties of which we need to write a link to the section (page) to which they lead.
You can see an example of a request under the spoiler, an example of this request is presented.
function GetNotebookList(token) {
//начало запроса
var request = new XMLHttpRequest;
//метод open
request.open("GET", "https://www.onenote.com/api/v1.0/notebooks", false);
//метод setRequestHeader
request.setRequestHeader("Authorization", "Bearer " + token);
//получение ответа
request.onreadystatechange = function (response) {
//обработка ответа
var notes = JSON.parse(this.responseText);
var length = notes.value.length;
//создание списка кнопок
var buttonList = document.createElement("div");
for (var i = 0; i < length; i++) {
var NotebookName = notes.value[i].name;
var sec = notes.value[i].self;
var b = document.createElement("button");
b.innerText = NotebookName;
b.id = notes.value[i].id;
var link = notes.value[i].sectionsUrl;
b.dataset.link = link;
buttonList.appendChild(b);
//обработка события нажатия на кнопку – переход на страницу +
// передача данных о книге, список секций которой необходимо загрузить
b.addEventListener("click", function (e) {
var link = this.dataset.link;
WinJS.Navigation.navigate("/pages/notebook/viewnotebook.html",link);
return null;
});
}
var buttonsDiv = document.getElementById("buttonsDiv");
buttonsDiv.appendChild(buttonList);
}
request.send();
return null;
}Tip: The x-ms-webview element is good for displaying page content .

Sending a POST request
In OneNote API, a POST request is used when creating new pages (notebooks, sections).
For example, if you want to add a new page, the query will be as follows
function PostNewPage(token) {
var body = document.getElementById("viewPage").innerHTML;
//начало запроса
var request = new XMLHttpRequest;
//метод open
request.open("POST", https://www.onenote.com/api/v1.0/pages, false);
//метод setRequestHeader
request.setRequestHeader('Content-Type', 'application/xhtml+xml', false);v
//метод setRequestHeader
request.setRequestHeader("Authorization", "Bearer " + token);
//получение ответа
request.onreadystatechange = function (response) {
//обработка ответа
}
request.send(body.name);
return null;
}
}Please note that in the POST request for adding a new page, we use the setRequestHeader method two times - once we determine the format of the data to be sent ( application / xhtml + xml ), then we set the authorization parameters.
The remaining requests are similar to those that we have already reviewed. Once again I want to draw your attention to the fact that you can test your request in the apigee.com interactive console or see the necessary request parameters on the OneNote Development Center website .
Working with the OneNote API is easy, I suggest you get started right away!

Sitelinks
- OneNote Development Center
- Apigee.com Interactive Console for OneNote API
- View course on publishing apps on the Windows Store
- Download Free or Trial Visual Studio
about the author

Alexandra Bogdanova, project manager, Customer and Partner Experience, Microsoft Russia. Participant in various conferences, meetings, hackathons, including the Microsoft Developer Tour and Microsoft Developer Conference.
Only registered users can participate in the survey. Please come in.
How interesting is integration with OneNote REST API for your projects?
- 52.9% Very interesting, we will explore the possibilities 36
- 17.6% Undecided , more information needed 12
- 29.4% Not interesting yet, we will keep in mind 20