title: Error in running this code - Add List item to Sharepoint online Lists via Azure functions in C#
body: <p>I am new to this and as my first, I'm trying to develop an Azure function to add a new item to column 'ID' to a Sharepoint online List via rest API in C#. I have written this code in the web portal of Azure and have adapted it into Visual Studio for the sake of troubleshooting. Please, anyone, provide some help as I cannot seem to get it working, Thanks.</p>
  
  <pre><code>using System;
  using System.Configuration;
  using System.Collections.Generic;
  using System.Linq;
  using System.Net;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;
  using Newtonsoft.Json.Linq;
  using System.Net.Http.Headers;
  using Newtonsoft.Json.Serialization;
  using System.Security;
  using System.Diagnostics;
  using Microsoft.SharePoint.Client;
  
  namespace ConsoleApp1
  {
  class Program
  {
      public static async Task&lt;string&gt; GetAuthTokenForSharePoint()
      {
          Console.WriteLine(" GetAuthTokenForSharePoint was executed!");
          HttpClient client = new HttpClient();
  
          string clientId = System.Configuration.ConfigurationManager.AppSettings["123aa123-1234-1234-b1c2-12ab0052c945"];
          string clientSecret = System.Configuration.ConfigurationManager.AppSettings["HdvsavdshavshjdvHhhhsdgahsgjhwqj08="];
          string tenantId = System.Configuration.ConfigurationManager.AppSettings["123a1a23-1ab4-4a44-b3c7-abc00d12345e"];
          string spTenantUrl = System.Configuration.ConfigurationManager.AppSettings["https://mytenant.sharepoint.com"];
          string spPrinciple = "00000003-0000-0ff1-ce00-000000000000";
          string spAuthUrl = "https://accounts.accesscontrol.windows.net/" + tenantId + "/tokens/OAuth/2";
  
          KeyValuePair&lt;string, string&gt;[] body = new KeyValuePair&lt;string, string&gt;[]
          {
      new KeyValuePair&lt;string, string&gt;("grant_type", "client_credentials"),
      new KeyValuePair&lt;string, string&gt;("client_id", $"{clientId}@{tenantId}"),
      new KeyValuePair&lt;string, string&gt;("resource", $"{spPrinciple}/{spTenantUrl}@{tenantId}".Replace("https://", "")),
      new KeyValuePair&lt;string, string&gt;("client_secret", clientSecret)
          };
  
          var content = new FormUrlEncodedContent(body);
          var contentLength = content.ToString().Length;
  
          string token = "";
          Console.WriteLine(content.ToString());
          using (HttpResponseMessage response = await client.PostAsync(spAuthUrl, content))
          {
              if (response.Content != null)
              {
                  Console.WriteLine("Something went wrong in getting token much earlier");
                  string responseString = await response.Content.ReadAsStringAsync();
                  JObject data = JObject.Parse(responseString);
                  token = data.Value&lt;string&gt;("access_token");
              }
              else
              {
                  Console.WriteLine("Something went wrong in getting token");
              }
          }
  
          return token;
      }
  
      public static async Task&lt;string&gt; GetDigestForSharePoint(string siteUrl, string token)
      {
          Console.WriteLine("GetDigestForSharePoint was executed!");
          HttpClient client = new HttpClient();
  
          client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
          client.DefaultRequestHeaders.Add("accept", "application/json;odata=verbose");
          StringContent content = new StringContent("");
  
          string spTenantUrl = System.Configuration.ConfigurationManager.AppSettings["https://mytenant.sharepoint.com"];
          string digest = "";
  
          // using (HttpResponseMessage response = await client.PostAsync())$"{spTenantUrl}{siteUrl}/_api/contextinfo"
  
          using (HttpResponseMessage response = await client.PostAsync("https://mytenant.sharepoint.com/sites/mySite", content))
          {
              if (response.IsSuccessStatusCode)
              {
                  string contentJson = response.Content.ReadAsStringAsync().Result;
                  JObject val = JObject.Parse(contentJson);
                  JToken d = val["d"];
                  JToken wi = d["GetContextWebInformation"];
                  digest = wi.Value&lt;string&gt;("FormDigestValue");
              }
          }
  
          return digest;
      }
  
      public static async Task CreateSharePointListItem(string siteUrl, string listName, string itemTitle)
      {
          Console.WriteLine("CreateSharePointListItem was executed!");
          try
          {
              var token = await GetAuthTokenForSharePoint();
              Console.WriteLine(token);
              var digest = await GetDigestForSharePoint(siteUrl, token);
  
              HttpClient client = new HttpClient();
              client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
              client.DefaultRequestHeaders.Add("accept", "application/json;odata=verbose");
              client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
              client.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");
  
              HttpContent content = new StringContent($"{{ '__metadata': {{ 'type': 'SP.ListItem' }}, 'Title': '{itemTitle}'}}");
              content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
              content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("odata", "verbose"));
  
              string spTenantUrl = System.Configuration.ConfigurationManager.AppSettings["https://mytenant.sharepoint.com"];
  
              using (HttpResponseMessage response = await client.PostAsync($"{spTenantUrl}{siteUrl}/_api/web/Lists/GetByTitle('{listName}')/items", content))
              {
                  if (!response.IsSuccessStatusCode)
                      //log.Error($"The REST call to SharePoint failed: {response.StatusCode.ToString()}.");
                      Console.WriteLine(response.StatusCode.ToString());
              }
          }
          catch (Exception ex)
          {
              //log.Error($"Could not write SharePoint list item: {ex}");
              Console.WriteLine(ex);
          }
      }
  
  
      public static async void Run()
      {
          Console.WriteLine("Run was executed!");
          await CreateSharePointListItem("/sites/mySite", "myList", "ID");
      }
  
      static void Main(string[] args)
      {
          Program.Run();
  
      }
  }
  </code></pre>
  
  <p>}</p>