Open the OneNote clients with the OneNote API

Learn how to open the OneNote native and online clients by using URLs returned by the OneNote API.

Last modified: January 22, 2016

Applies to: OneNote service

In this article
Opening OneNote from an Android app
Opening OneNote from an iOS app
Opening OneNote from a Windows Phone app
Opening OneNote from a Windows Store app

Note Note

See this topic on our new documentation site for consumer and enterprise OneNote APIs.

When your app successfully creates a page by sending a POST request to the pages endpoint, the API returns a 201 status code and the links property, which is a JSON object that contains two URLs. The following example shows the (abbreviated) URLs in the HTTP response.

{
    "links": {
        "oneNoteClientUrl": {
            "href": "onenote:https://..."
        },
        "oneNoteWebUrl": {
            "href": "https://..."
        }
    }
}

You can use the URLs to open the new page in the native or online OneNote client.

  • Use oneNoteClientUrl to open the native client if it is already installed on the device. This URL includes the onenote prefix.

  • Use oneNoteWebUrl to open OneNote Online if the default browser on the device supports OneNote Online.

OneNote supports many languages. When your app opens the native client, it opens the language-specific version if one is installed on the device. Otherwise, the platform language setting is used. When your app opens OneNote Online, the browser language setting determines which language is used.

The code examples in this article first check the status code of the response and then parse the JSON to extract the URLs.

Important noteImportant

The following code examples are from the samples on GitHub. They are for demonstration purposes only and are not intended as production code. To make the code flow easier to understand, things like detailed user-input validation are not included. Carefully review your code for potential code-quality and security issues before you publish your app.

The following example gets the OneNote client URLs from the JSON response. It uses the Google GSON library (http://code.google.com/p/google-gson/) to extract the two URLs. In the example, mUrlConnection is the HttpsURLConnection object used to make the POST request to the OneNote API. The response object is an instance of a class defined in your code to store the response property values.

Note Note

On Android devices, you need to enclose GUIDs in the oneNoteClientUrl with braces, as shown in the example.

You can get the full Android code sample on GitHub.


public ApiResponse getResponse() throws Exception {
   /* Retrieve the HTTP response code and message from the connection object */
   int responseCode = mUrlConnection.getResponseCode();
   String responseMessage = mUrlConnection.getResponseMessage();
   String responseBody = null;

   /* Verify that the new page was created successfully, 
      with HTTP status = 201 */
   if ( responseCode == 201) {
      InputStream is = mUrlConnection.getInputStream();

      /* Verify that this byte array is big enough */
      byte[] b1 = new byte[1024];
      StringBuffer buffer = new StringBuffer();

      /* Copy the body of the response into the new string */
      /* again, make sure the buffer is big enough! */
      while ( is.read(b1) != -1)
         buffer.append(new String(b1));

      /* When the returned data is complete, close the connection 
         and convert the byte array into a string */
      mUrlConnection.disconnect();
      responseBody =  buffer.toString();
   }

   /* Create a new JSON object, and an object to hold the response URLs */
   JSONObject responseObject = null;
   ApiResponse response = new ApiResponse();
   try {

      /* Store and verify the HTTP response code */
      response.setResponseCode(responseCode);
      response.setResponseMessage(responseMessage);
      if ( responseCode == 201) {

         /* Create the object and retrieve the two URLs */
         responseObject = new JSONObject(responseBody);
         String clientUrl = responseObject.getJSONObject(
            "links").getJSONObject("oneNoteClientUrl").getString("href");
         String webUrl = responseObject.getJSONObject(
            "links").getJSONObject("oneNoteWebUrl").getString("href");
         response.setOneNoteClientUrl(clientUrl);
         response.setOneNoteWebUrl(webUrl);
      }
   } catch (JSONException ex) {

      /* If the JSON was malformed or incomplete... */
      String msg = ex.getMessage();
      msg = msg;
   }
   return response;
}

Then, using those response object properties, your app can open OneNote Online, as shown in the following example.


if (response.getReseponseCode() == 201) {
    Uri uriUrl = Uri.parse(response.getOneNoteWebUrl);  
    Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl); 
    startActivity(launchBrowser);
}

When using the oneNoteClientURL to open the native OneNote client on an Android device, you must surround the GUID strings with braces {…} before starting the Intent. The following example shows how to do that.


if (response.getReseponseCode() == 201) {
   // Get the URL from the OneNote API JSON response
   String onenoteClientUrl = obtainClientLinkFromJSONResponse();
   String androidClientUrl = 
      onenoteClientUrl.replaceAll(
      "=([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})&",
      "={$1}&");
  // Open the URL: Open the newly created OneNote page
  Uri uriUrl = Uri.parse(androidClientUrl);  
  Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl); 
  startActivity(launchBrowser);
}

The following example gets the OneNote client URLs from the JSON response. It uses the AFNetworking library (http://afnetworking.com/) to extract the two URLs. In the example, created is a pointer to the ONSCPSStandardResponse object used to store the response values, and responseObject holds the parsed JSON.

You can get the full iOS code sample on GitHub.


/* Import the JSON library */
#import "AFURLRequestSerialization.h"

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  if(delegate) {
    int status = [returnResponse statusCode];
    ONSCPSStandardResponse *standardResponse = nil;
    if (status == 201) {
      ONSCPSCreateSuccessResponse *created = 
        [[ONSCPSCreateSuccessResponse alloc] init];
      created.httpStatusCode = status;
      NSError *jsonError;
      NSDictionary *responseObject = 
        [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&jsonError];
      if(responseObject && !jsonError) {
        created.oneNoteClientUrl = ((NSDictionary *)
          ((NSDictionary *)responseObject[@"links"])[@"oneNoteClientUrl"])[@"href"];
        created.oneNoteWebUrl = ((NSDictionary *)
          ((NSDictionary *)responseObject[@"links"])[@"oneNoteWebUrl"])[@"href"];                }
        standardResponse = created;
    }
    else {
      ONSCPSStandardErrorResponse *error = [[ONSCPSStandardErrorResponse alloc] init];
      error.httpStatusCode = status;
      error.message = [[NSString alloc] initWithData:returnData 
        encoding:NSUTF8StringEncoding];
      standardResponse = error;
    }
    // Send the response back to the client.
    if (standardResponse) {
      [delegate exampleServiceActionDidCompleteWithResponse: standardResponse];
    }
  }
}

Now that you've parsed the URLs from the response, you can open OneNote by using the following code. Use oneNoteClientUrl to open the installed OneNote client or oneNoteWebURL to open OneNote Online.


NSURL *url = [NSURL URLWithString:standardResponse.oneNoteWebUrl];
[[UIApplication sharedApplication] openURL:url];

The following example gets the OneNote client URLs from the JSON response. It uses the Newtonsoft Json.net library (http://json.codeplex.com/) to extract the two URLs. In this example, response is the object returned by the POST operation. Depending on whether the POST succeeds, standardResponse is an object created as either a CreateSuccessResponse or StandardErrorResponse, which are classes defined elsewhere in the sample.

Note Note

On Windows Phone devices, you need to enclose GUIDs in the oneNoteClientUrl with braces, as shown in the example.

You can get the full Windows Phone 8 code sample on GitHub.

        
private async static Task<StandardResponse> 
  TranslateResponse(HttpResponseMessage response)
{
  StandardResponse standardResponse;
  if (response.StatusCode == HttpStatusCode.Created)
    {
      dynamic responseObject = 
        JsonConvert.DeserializeObject(await 
        response.Content.ReadAsStringAsync());
      standardResponse = new CreateSuccessResponse
        {
          StatusCode = response.StatusCode,
          OneNoteClientUrl = responseObject.links.oneNoteClientUrl.href,
          OneNoteWebUrl = responseObject.links.oneNoteWebUrl.href
        };
    }
    else
    {
      standardResponse = new StandardErrorResponse
        {
          StatusCode = response.StatusCode,
          Message = await response.Content.ReadAsStringAsync()
        }; 
    }
}

The following example opens the Windows Phone OneNote Online client using the extracted oneNoteWebUrl.


  Windows.System.Launcher.LaunchUriAsync(new Uri(standardResponse.OneNoteWebUrl));

When using the oneNoteClientUrl on a Windows Phone device, surround the GUID strings with braces {…} before calling LaunchUriAsync. The following code shows how to use a regular expression to add those braces, and then open the OneNote native client.


  Regex guidRegex = 
    new Regex(@"=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})&",
  RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
  var matches = guidRegex.Matches(standardResponse.OneNoteClientUrl);
  if (matches.Count == 2)
  {
    standardResponse.OneNoteClientUrl = 
      standardResponse.OneNoteClientUrl.Replace(matches[0].Groups[1].Value, 
      "{" + matches[0].Groups[1].Value + 
      "}").Replace(matches[1].Groups[1].Value, 
      "{" + matches[1].Groups[1].Value + "}");
  }
  Windows.System.Launcher.LaunchUriAsync(
    new Uri(standardResponse.OneNoteClientUrl));

Windows Phone app code is essentially the same as the Windows Store app code.

The following example gets the OneNote client URLs from the JSON response. It uses the Newtonsoft Json.net library (http://json.codeplex.com/) to extract the two URLs. In this example, response is the object returned by the POST operation. Depending on whether the POST succeeds, the code creates a standardResponse that is either a CreateSuccessResponse or StandardErrorResponse. Those classes are defined elsewhere in the sample.

You can get the full Windows Store code sample on GitHub.

        
private async static Task<StandardResponse> 
    TranslateResponse(HttpResponseMessage response)
{
  StandardResponse standardResponse;
  if (response.StatusCode == HttpStatusCode.Created)
    {
      dynamic responseObject = 
        JsonConvert.DeserializeObject(await 
        response.Content.ReadAsStringAsync());
      standardResponse = new CreateSuccessResponse
        {
          StatusCode = response.StatusCode,
          OneNoteClientUrl = responseObject.links.oneNoteClientUrl.href,
          OneNoteWebUrl = responseObject.links.oneNoteWebUrl.href
        };
    }
    else
    {
      standardResponse = new StandardErrorResponse
        {
          StatusCode = response.StatusCode,
          Message = await response.Content.ReadAsStringAsync()
        };
    }
  return standardResponse;
}

The following code opens OneNote using the extracted URLs. You can use the code with oneNoteClientUrl to open the native client, or with oneNoteWebUrl to open OneNote Online.

Windows.System.Launcher.LaunchUriAsync(new Uri(standardResponse.OneNoteClientUrl));

Windows Store app code is essentially the same as the Windows Phone app code.

Show: