Search code examples
c#onenote-api

OneNote API Create Notebook


I'm getting a "Bad Request" when I try to create a new OneNote API Notebook.

 private async Task<string> CreateSimpleNotebook(string notebookName,  string apiRoute)
    {
        var client = new HttpClient();

          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        }
        catch (Exception ex)
        {
            string tempEx = ex.ToString();
        }

        var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute )
        {
            Content = new StringContent("{ name : '" + WebUtility.UrlEncode(notebookName) + "' }", Encoding.UTF8, "application/json")
        };

        HttpResponseMessage response = await client.SendAsync(createMessage);

        return response.Headers.Location.ToString();
    }

And I call the method with the following:

      string url = "https://graph.microsoft.com/v1.0/me/onenote/notebooks/";
        //   string url = "https://www.onenote.com/api/v1.0/me/notes/notebooks/";

        string tempResponse = await CreateSimpleNotebook("EMRTest2", url);

Here is the response:

    {StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  client-request-id: acacd4f5-8738-4c46-8150-17aa23413eb5
  request-id: acacd4f5-8738-4c46-8150-17aa23413eb5
  Transfer-Encoding: chunked
  x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"South Central US","Slice":"SliceB","Ring":"NA","ScaleUnit":"002","Host":"AGSFE_IN_10","ADSiteName":"SAN"}}
  Duration: 772.4124
  Cache-Control: private
  Date: Sun, 19 Nov 2017 20:59:10 GMT
  Content-Type: application/json
}}

Solution

    1. You should use Content-Type JSON
    2. The name of the property you are looking for is not "name", it is "displayName"

    Additionally, crafting JSON by appending string is not best practice - I recommend using a JSON library, like NewtonSoft JSON.NET.