In this blog post, I’ll show how to use SharePoint REST API, in a C# console application i.e., .NET server side, to fetch ListItems from a SharePoint Online List.
Just like JavaScript, we can invoke REST calls directly from a .NET C# application, here using HTTPClient.
In the following code snippet, I am fetching the first ListItem of a SharePoint Online’s external list. The output of this call will be a JSON string.
C#
private static async Task<string> RESTCall() { string RESTURL = "{0}/_api/web/lists/GetByTitle('ODataList_Manual')/items?$top=1"; string webUrl = "https://domain.sharepoint.com"; string USER = "piyush@domain.onmicrosoft.com"; var passWord = new SecureString(); string PWD = "yourPassword"; PWD.ToList().ForEach(passWord.AppendChar); var credential = new SP.SharePointOnlineCredentials(USER, passWord); using (var handler = new HttpClientHandler() { Credentials = credential }) { //Get authentication cookie Uri uri = new Uri(webUrl); handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri)); //Invoke REST API using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync(string.Format(RESTURL, webUrl)).ConfigureAwait(false); response.EnsureSuccessStatusCode(); string jsonData = await response.Content.ReadAsStringAsync(); Debug.Write(jsonData); return jsonData; } } }
Output
{ "odata.metadata": "https://domain.sharepoint.com/_api/$metadata#SP.ListData.ODataList_x005f_ManualListItems", "value": [{ "odata.type": "SP.Data.ODataList_x005f_ManualListItem", "odata.id": "e2dcb7f0-304c-4b4f-a291-f60b8e15b80a", "odata.editLink": "Web/Lists(guid'5d80cee7-8ce4-4201-b172-a6d16ddbf953')/GetItemByStringId('__cg410013000300230043008300g800013001300')", "FileSystemObjectType": 0, "Id": 0, "ServerRedirectedEmbedUrl": "", "BdcIdentity": "__cg410013000300230043008300g800013001300", "OrderID": 10248, "ProductID": 11, "UnitPrice": "14.0000", "Quantity": 12, "Discount": 0.0 }] }
Key Takeaways
- I am using the OData Top System Query Option ($top), to limit the number of returned items to one. For SharePoint, we can achieve the same by passing an empty CAML query, with RowLimit option set to one.
- I am running this code from a C# console application. I just need to reference the SharePoint Client dll in order to get the definition of SharePointOnlineCredentials.
- In the output JSON, value attribute is of type array. For multiple items, it will contain as many JSON objects. However, as I have requested only a single item here, this attribute, for this particular case, only contains a single object.
Thank You, This code worked very well…
LikeLike
🙂
LikeLike
can you tell me how to call this from main method
LikeLike
You can directly call the async method. Since, I am returning a Task here, you can call the method like, RESTCall().Result. Adding the Result to the async call will force it to run synchronously.
For more details, check out the following post,
How to call an async method from a console app main method
LikeLike
I am getting this error and why I am getting the response back in xml !
There was an exception: System.AggregateException: One or more errors occurred. —> System.Xml.XmlException: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ThrowWithoutLineInfo(String res)
at System.Xml.XmlTextReaderImpl.ParseDoctypeDecl()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at Microsoft.SharePoint.Client.Idcrl.IdcrlAuth.DoGet(String url)
at Microsoft.SharePoint.Client.Idcrl.IdcrlAuth.RequestFederationProviderInfo(String domainname)
at Microsoft.SharePoint.Client.Idcrl.IdcrlAuth.GetFederationProviderInfo(String domainname)
at Microsoft.SharePoint.Client.Idcrl.IdcrlAuth.InitFederationProviderInfoForUser(String username)
at Microsoft.SharePoint.Client.Idcrl.IdcrlAuth.GetServiceToken(String username, String password, String serviceTarget, String servicePolicy)
at Microsoft.SharePoint.Client.Idcrl.SharePointOnlineAuthenticationProvider.GetAuthenticationCookie(Uri url, String username, SecureString password, Boolean alwaysThrowOnFailure, EventHandler
1 executingWebRequest)
1 executingWebRequest)at Microsoft.SharePoint.Client.SharePointOnlineCredentials.GetAuthenticationCookie(Uri url, Boolean refresh, Boolean alwaysThrowOnFailure)
at Microsoft.SharePoint.Client.SharePointOnlineCredentials.GetAuthenticationCookie(Uri url)
at TestRestApiConnection.Program.<callSpApi>d__1.MoveNext() in Program.cs:line 64
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at TestRestApiConnection.Program.Main(String[] args) in Program.cs:line 34
---> (Inner Exception #0) System.Xml.XmlException: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ThrowWithoutLineInfo(String res)
at System.Xml.XmlTextReaderImpl.ParseDoctypeDecl()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at Microsoft.SharePoint.Client.Idcrl.IdcrlAuth.DoGet(String url)
at Microsoft.SharePoint.Client.Idcrl.IdcrlAuth.RequestFederationProviderInfo(String domainname)
at Microsoft.SharePoint.Client.Idcrl.IdcrlAuth.GetFederationProviderInfo(String domainname)
at Microsoft.SharePoint.Client.Idcrl.IdcrlAuth.InitFederationProviderInfoForUser(String username)
at Microsoft.SharePoint.Client.Idcrl.IdcrlAuth.GetServiceToken(String username, String password, String serviceTarget, String servicePolicy)
at Microsoft.SharePoint.Client.Idcrl.SharePointOnlineAuthenticationProvider.GetAuthenticationCookie(Uri url, String username, SecureString password, Boolean alwaysThrowOnFailure, EventHandler
at Microsoft.SharePoint.Client.SharePointOnlineCredentials.GetAuthenticationCookie(Uri url, Boolean refresh, Boolean alwaysThrowOnFailure)
at Microsoft.SharePoint.Client.SharePointOnlineCredentials.GetAuthenticationCookie(Uri url)
at TestRestApiConnection.Program.d__1.MoveNext() in Program.cs:line 64<—
LikeLike
is it possible to connect sharepoint via access token instead of sharepoint credentials ?
LikeLike
SharepointonlineCredentails method is NO MORE in use.
https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/using-csom-for-dotnet-standard
Need the solution using the new method.
LikeLike