Calling external REST service from a SharePoint hosted App using the Web proxy

In this blog post we will explain one of the ways to call an external REST service from the JS code of a SharePoint App. In order to prevent cross-site scripting attacks the browsers would not allow your code to make calls to external services, it will allow you to call only the domain from which the application is loaded.

One way to work around this is to use the Web Proxy, provided by SharePoint 2013. The approach is simple – your JS code will call a specific REST endpoint (/_api/SP.WebProxy.invoke) with all the parameters needed for the actual call. The SharePoint will then call the actual service and pass the response back. This way the client browser communicates only with the SharePoint app web.

So how do we implement this? First we should make sure that the SP.js file is referenced and create a new SP.WebRequestInfo object. We should set all the properties needed for the request, like URL, method, etc. As the call is asynchronous we should also provide a success and error functions. Finally we call the load method in the $(document).ready event.

Before firing this off we should add the remote domain as trusted. This is another security feature that prevents the SharePoint from making calls to unwanted domains, in case that there is a malicious JavaScript code executed in the app. To add our domain to the allowed list the following RemoteEndpoint entry should be added to the app manifest:

One consideration that is notable to mention is that the SharePoint front-end server should have access to the remote endpoint. In some situations there might be a firewall that prevents the requests from being executed.