Make simple captures with the OneNote API

Learn how to use the Microsoft OneNote API to capture simple HTML text and images in the user's OneNote notebook.

Last modified: April 18, 2014

Applies to: OneNote service

In this article
Creating a simple page in an Android app
Creating a simple page in an iOS app
Creating a simple page in a Windows Phone app
Creating a simple page in a Windows Store app
Creating a simple page using REST

One simple way to create new pages in your user's OneNote notebooks is to do a POST to the OneNote pages REST endpoint, sending a lightweight HTML document as the contents of the message body, like in the following example.


<!DOCTYPE html>
<html>
  <head>
    <title>A simple page with a block of HTML</title>
  </head>
  <body>
    <p>This is a simple page block.</p>
  </body>
</html>

The API also accepts multi-part data in the POST body. For simpler programming and consistency in your app, you might choose to use just multi-part POSTs.

The following code shows the high-level structure of a multi-part POST body, where the page structure is defined in the Presentation part, and image binary data is sent in the imageBlock-1 part.


Content-Type:multipart/form-data; boundary=MyAppPartBoundary

--MyAppPartBoundary
Content-Disposition:form-data; name="Presentation"
Content-type:text/html

... presentation part html data ...

--MyAppPartBoundary
Content-Disposition:form-data; name="imageBlock-1"
Content-type:image/jpeg

... image binary data ...

--MyAppPartBoundary
Content-Disposition:form-data; name="htmlToRender-1"
Content-type:text/html

... html data ...

--MyAppPartBoundary--


To better understand the over-the-wire differences between simple POSTs and multi-part POSTS, more examples of REST requests are shown in the last section of this article.

When we say the pages endpoint can accept posts of "HTML", we don't mean all tags supported in HTML4, XHTML, CSS, HTML5, and so on. The OneNote API creates pages tuned for "note taking": lists, images, file attachments, paragraphs, headings, and so on. Active content such as a canvas in HTML5 is not part of OneNote. Instead, the OneNote API accepts a reduced set of HTML that better fits how people use OneNote. For more information, see OneNote API HTML tag support. If it's not listed in that topic, it's almost certain to be ignored.

The OneNote API only accepts UTF-8 data. Be sure that all requests are encoded that way, and your content-type headers indicate that as well.

Important noteImportant

Before even a simple POST like the ones shown here can succeed, you need to Get a client ID for use with the OneNote API (or package ID for a Windows Store application), and your app has to Authenticate the user for the OneNote API. If you don't supply a valid OAuth token with your request, it will fail.

TipTip

As with most code samples in documentation, these code samples should not be considered production-ready code. Things like detailed user-input validation have been left out to make it easier to understand the code flow. Carefully review your code for potential code-quality and security issues before you publish your app.

The following code sample builds a basic multi-part request that contains a very simple HTML page with bold and italic text. There are three parts of code in the following. The first defines the pages REST endpoint, where the app will send the data. The second, ConnectForMultipart method adds the content type and authorization headers to the request. The third builds the request body with the HTML. Be aware that, in this example, the HTML is contained in a part named "Presentation". The OneNote API recognizes that name and expects the HTML-based page structure to be inside that part.

This code is taken from the SendPageCreateAsyncTask class in the Android code sample on GitHub. For more information, see Get the OneNote API sample applications.


/* The first part: define a constant for the REST endpoint */
private final String PAGES_ENDPOINT = "https://www.onenote.com/api/v1.0/pages";

/* The second part: build the HTTP connection object, adds the 
   Content-Type and Authorization headers, and makes the connection */
private void connectForMultipart(String endpoint) throws Exception {
  mUrlConnection = (HttpsURLConnection) ( new URL(endpoint)).openConnection();
  mUrlConnection.setDoOutput(true);
  mUrlConnection.setRequestMethod("POST");
  mUrlConnection.setDoInput(true);
  mUrlConnection.setRequestProperty("Connection", 
    "Keep-Alive");
  mUrlConnection.setRequestProperty("Content-Type", 
    "multipart/form-data; boundary=" + BOUNDARY);
  mUrlConnection.setRequestProperty("Authorization", 
    "Bearer " + mAccessToken);
  mUrlConnection.connect();
  mOutputStream = mUrlConnection.getOutputStream();
}

/* The third part: build the POST request part with the HTML */
public ApiResponse createSimplePage() {
  try {
    this.connectForMultipart(PAGES_ENDPOINT);
    String date = getDate();
    String simpleHtml = 
      "<html>" +
      "  <head>" +
      "    <title>A page created from basic HTML (Android Sample)</title>" +
      "    <meta name=\"created\" content=\"" + date + "\" />" +
      "  </head>" +
      "  <body>" +
      "    <p>This is a page that just contains some simple " +
      "    <i>formatted</i> <b>text</b></p>" +
      "  </body>" +
      "</html>";
    this.addFormPart("Presentation", "application/xhtml+xml", simpleHtml);
    this.finishMultipart();
    ApiResponse response = this.getResponse();
    return response;
  } catch (Exception ex) {
    String test = ex.getMessage();
  }
  return null;
}

This code sample creates a basic OneNote page from HTML by placing the HTML directly in the HTTPS request body. It doesn't use the multi-part format. The code sample also adds the Content-Type and Authentication headers to the POST request. Although this code uses a variable named "presentation", it isn't using that variable identifier like it was the "Presentation" part of a multi-part message. This code also verifies that the Windows Live Connect session status indicates the user is logged in.

This code is taken from the ONSCPSCreateExamples class in the iOS code sample on GitHub. For more information, see Get the OneNote API sample applications.


// The endpoint for the OneNote API
NSString *const PagesEndPoint = @"https://www.onenote.com/api/v1.0/pages";

- (void)createSimplePage {
    NSString *date = [ONSCPSCreateExamples getDate];
    NSString *simpleHtml = [NSString stringWithFormat:
        @"<html>"
        "  <head>"
        "    <title>A page created from basic HTML (iOS Sample)</title>"
        "    <meta name=\"created\" content=\"%@\" />"
        "  </head>"
        "  <body>"
        "    <p>This is a page that just contains some simple "
        "    <i>formatted</i> <b>text</b></p>"
        "  </body>"
        "</html>", date];
    NSData *presentation = [simpleHtml dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest * request = 
        [[NSMutableURLRequest alloc] 
        initWithURL:[[NSURL alloc] initWithString:PagesEndPoint]];
    request.HTTPMethod = @"POST";
    request.HTTPBody = presentation;
    [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
    if (liveClient.session)
    {
        [request setValue:[@"Bearer " 
        stringByAppendingString:liveClient.session.accessToken] 
        forHTTPHeaderField:@"Authorization"];
    }
    currentConnection = 
        [[NSURLConnection alloc] initWithRequest:request 
        delegate:self startImmediately:YES];
}

This code sample creates a basic OneNote page from HTML by placing the HTML directly in the HTTPS request body. It doesn't use the multi-part format. The code sample defines a constant for the OneNote API pages endpoint, adds the Content-Type and Authentication headers to the POST request, forms the HTML, checks the status of the Login session, and then calls the API. The EndRequest method handles the results returned from the API, described more fully in the Debug and handle errors with the OneNote API topic.

This code is taken from the Windows Phone code sample on GitHub. For more information, see Get the OneNote API sample applications.


// v1.0 Endpoint
private const string PAGESENDPOINT = "https://www.onenote.com/api/v1.0/pages";
        
private async void btn_CreateSimple_Click(object sender, RoutedEventArgs e)
  {
    StartRequest();
    string date = GetDate();
    string simpleHtml = 
      "<html>" +
      "  <head>" +
      "    <title>A page created from basic HTML (WinPhone8 Sample)</title>" +
      "    <meta name=\"created\" content=\"" + date + "\" />" +
      "  </head>" +
      "  <body>" +
      "    <p>This is a page that just contains some simple " +
      "    <i>formatted</i> <b>text</b></p>" +
      "   </body>" +
      "</html>";

    // Create the request message
    var createMessage = new HttpRequestMessage(HttpMethod.Post, PAGESENDPOINT)
      {
        Content = new StringContent(simpleHtml, 
          System.Text.Encoding.UTF8, "text/html")
      };
    HttpClient httpClient = new HttpClient();
    // Add Authorization header
    httpClient.DefaultRequestHeaders.Authorization = 
      new AuthenticationHeaderValue("Bearer", m_AccessToken);

    // API only supports JSON return type.
    httpClient.DefaultRequestHeaders.Accept.Add(
      new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = 
      await httpClient.SendAsync(createMessage);
    await EndRequest(response);
}

This code sample creates a basic OneNote page from HTML by placing the HTML directly in the HTTPS request body. It does not use the multi-part format. The code sample defines a constant for the OneNote API pages endpoint, creates the HTTP request client, and adds headers to the request. The code then formats and adds the HTML body to the request and calls the API. The TranslateResponse method handles the results returned from the API, described more fully in the Debug and handle errors with the OneNote API topic.

This code sample is taken from the OneNoteCloudCreatePagesSample class in the Windows Store code sample on GitHub. For more information, see Get the OneNote API sample applications.


private static readonly Uri PagesEndPoint = new Uri("https://www.onenote.com/api/v1.0/pages");
 
async public Task<StandardResponse> CreateSimplePage(bool debug)
  {
    var client = new HttpClient();

    // The API only supports JSON return type.
    client.DefaultRequestHeaders.Accept.Add(
      new MediaTypeWithQualityHeaderValue("application/json"));
 
    // This allows you to see what happens when an unauthenticated call is made.
    if (this.IsAuthenticated)
      {
        client.DefaultRequestHeaders.Authorization = 
          new AuthenticationHeaderValue(
            "Bearer", this._authClient.Session.AccessToken);
      }
    string date = GetDate();
    string simpleHtml = 
      "<html>" +
      "  <head>" +
      "    <title>A page created from basic HTML (Windows 8 Sample)</title>" +
      "    <meta name=\"created\" content=\"" + date + "\" />" +
      "  </head>" +
      "  <body>" +
      "    <p>This is a page that just contains some simple " +
      "    <i>formatted</i> <b>text</b></p>" +
      "  </body>" +
      "</html>";
    var createMessage = 
      new HttpRequestMessage(HttpMethod.Post, PagesEndPoint)
        {
          Content = new StringContent(simpleHtml, 
            System.Text.Encoding.UTF8, "text/html")
        };
    HttpResponseMessage response = await client.SendAsync(createMessage);
    return await TranslateResponse(response);
}

The following HTTP requests show the REST-style headers and body to create a simple page. The first example shows a request where the HTML is placed directly in the request body, without any multi-part syntax. That syntax is simple and fast to create, but because image and file data can't be included directly in the same request, it has limitations for apps capturing data directly from the device.

For more information about the REST-focused API, see OneNote POST pages.


POST https://www.onenote.com/api/v1.0/pages

Content-Type:text/html 
Authorization:Bearer tokenString

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the captured OneNote page</title>
    <meta name="created" value="2013-06-11T12:45:00.000-8:00"/>
  </head>
  <body>
    <p>This is a simple Presentation block.</p>
  </body>
</html>

This next code sample shows the same request above, but formatted using a multi-part message. The part is named "Presentation", which is a special name recognized by the OneNote API as containing the page HTML.


POST https://www.onenote.com/api/v1.0/pages

Content-Type:multipart/form-data; boundary=MyAppPartBoundary
Authorization:Bearer tokenString

--MyAppPartBoundary
Content-Disposition:form-data; name="Presentation"
Content-type:text/html

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the captured OneNote page</title>
    <meta name="created" value="2013-06-11T12:45:00.000-8:00"/>
  </head>
  <body>
    <p>This is a very simple Presentation block.</p>
  </body>
</html>

--MyAppPartBoundary--


Show:
© 2014 Microsoft