0

Is there a way to call external REST api in SharePoint wsp? I am having REST api to particular site from where I have to bring the data. I know that we can call in javascript easily by using SP.Proxy (for cross domain using app model). But if I want to use the same thing in SharePoint 2013 farm solution with C# code, what is the way? Do I need to add any assembly references? This example work in SharePoint farm solution?

0

The link that you shared is one of the ways. We had to simulate a timer job by accessing AppWeb List items from Console Application and we used the same link you had shared to get it done, this way we did not face cross domain request issues. It basically creates an HTTP Web request using the REST endpoint that we pass in to the request.

You can change the return type as either json or xml/atom. If you chose json, then you will have to add json parser like Newtonsoft.json in the project as C# does not natively parse json but with XML it is straight forrward.

static XmlNamespaceManager xmlnspm = new XmlNamespaceManager(new NameTable());  
    static Uri sharepointUrl = new Uri("Site URL/");  
    static void Main(string[] args)  
    {  
        xmlnspm.AddNamespace("atom", "http://www.w3.org/2005/Atom");  
        xmlnspm.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");  
        xmlnspm.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");  
        NetworkCredential cred = new System.Net.NetworkCredential("username", password", "domain");  
        HttpWebRequest listRequest = (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "_api/Web/lists/getByTitle('List Name')/items");  
        listRequest.Method = "GET";  
        listRequest.Accept = "application/atom+xml";  
        listRequest.ContentType = "application/atom+xml;type=entry";  
        listRequest.Credentials = cred;  
        HttpWebResponse listResponse = (HttpWebResponse)listRequest.GetResponse();  
        StreamReader listReader = new StreamReader(listResponse.GetResponseStream());  
        var listXml = new XmlDocument();  
       listXml.LoadXml(listReader.ReadToEnd());  


        //Method 1 Seperate node list  
        var titleList = listXml.SelectNodes("//atom:entry/atom:content/m:properties/d:Title", xmlnspm);  
        var idList = listXml.SelectNodes("//atom:entry/atom:content/m:properties/d:ID", xmlnspm);  
        int i = 0;  
        foreach (XmlNode title in titleList)  
        {  
            Console.WriteLine(title.InnerXml+" "+idList[i++].InnerXml);  
        }  
      }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.