Exposing a REST API from your Apprenda hosted Service

Follow

REST Support

As part of the 2.5 release, the Apprenda platform added support for deployment of REST services which will facilitate lightweight access to your services from JavaScript in your UIs. This example will use Json encoding however POX (Plain Old XML) is also supported. What I will cover here is a very simple example of using a REST based AJAX call from my UI to my service. I won't get into the configuration at all, but if you have any questions feel free to ask in the comments.

Simple REST API Example

The goal for this example is to use AJAX from my UI to retrieve information from a REST based service. There are some challenges when working with WCF Rest services, in particular having to host your services in your UI to get them to run locally due to cross site scripting issues. I'll show you how you can get around this issue using Routing.

The REST Service

To begin with let's jump right into the service code, starting with the contract:

[ServiceContract]
public interface IRestService
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string GetLoggedInUser();
}

We are defining a ServiceContract with exactly one method called GetLoggedInUser. By using the WebGet attribute we are indicating that we want this method to be invoked through the REST programming model and additionally we are specifying that we would like the response format to be Json. Other than that nothing special here. For the service itself we will be making use of the Apprenda API to retrieve the currently logged in user's name through UserContext.

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class RestService : IRestService
{
public string GetLoggedInUser()
{
return UserContext.Instance.CurrentUser.FirstName;
}
}

The current implementation of WCF REST requires you to use the ASP.NET Compatibility attribute in order to indicate that your service will be using a REST based endpoint. In the implementation of our GetLoggedInUser method we are simply retrieving the first name of the currently logged in user through Apprenda's UserContext. In the case of local development this context is built entirely from the information provided in your SaaSGrid.cfg.xml which will allow you to test/debug without having to deploy to Apprenda.

Invoking the REST Service

With the service all setup now we can move on to the client side which in this case is going to be an AJAX call from our UI. We are going to use JQuery to make the AJAX call and use the result to create a simple "Hello name" example.

First define our content div:

<div id="message"></div>

And then the JavaScript:

<script type="text/javascript">

var baseUrl = "REST/json/RestService/IRestService/";

function getUser() {
$.ajax({
type: 'GET',
url: baseUrl + "GetLoggedInUser",
dataType: "json",
success: function (result) {
$("#message").append("Hello " + result);
},
error: function (result) {
alert(result.responseText);
}
});
}

$(document).ready(function () {
getUser();
});

</script>

The important thing to note here is the baseUrl. In Apprenda your REST services will end up being hosted at a specific location. The format for this location is defined as: http(s)://yourdomain/REST/(json|pox)/serviceName/ServiceContract/. As you can see you can use a relative path from within your UI without issue.

In order to make this work smoothly from local development to deployed Apprenda services you can make use of routing in your UI. When you run locally you will have to host the services within your UI in order to avoid cross-site scripting issues anyway so setting up the routing will make the transition from local to deployed seamless. For our example here is how the routing would be set up in Global.asax.cs:

public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new ServiceRoute("REST/json/RestService/IRestService", new ServiceHostFactory(), typeof(RestService.RestService)));
}

protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}

What this does is allow you to easily self host your services within your UI to test your REST API and then when your code is deployed the hosting and routing will be handled by Apprenda which will allow your services to take advantage of the high availability and scalability that Apprenda provides for you without having to change any of your code.

I have packaged a copy of the sample that has all of the necessary configuration and should run both locally and deployed to Apprenda without modifications.

Have more questions? Submit a request

Comments

  • Avatar
    Anilraj

    Can you please share me the sample code

  • Avatar
    Bernie Herdan

    Hi Anilraj,

    I am attaching the sample project used for this example.

    Please let me know if you have any other question,

    Bernie

  • Avatar
    Nic Bedford

    Could you leas help out with some more details on the configuration aspect of using a REST service. I have viewed the contents of the Taskr With REST.zip posted above, but it shows a behaviourExtension using SaaSGrid.API.Local (I am assuming this needs to be changed to SaaSGrid.API.Remote?) and it also shows endpoints containing localhost.

    So far I have been unsuccessful in calling an Apprenda hosted REST service from outside of the Apprenda environment, at the moment I am just using a c# test app and HttpWebRequest to attempt to access the Apprenda hosted service:

    request = WebRequest.Create("http://apps.yourdomain/rest/pox/HelloService/IHelloRest") as HttpWebRequest;
    request.Method = "POST";

     

    Thanks, Nic

  • Avatar
    Sriram

    Just reviving this thread...

    1)  What is the best way to access an Apprenda-hosted service from an application (desktop or web) that runs outside the Apprenda environment? 

    2)  Standalone reporting tools like StoneField have the capability to access remote SQL Server Databases for creating custom reporting.  Is it possible to have an Apprenda-hosted service return tenant-context-based connection string for use from StoneField or SSRS? 

  • Avatar
    Bryan Gregorius

    Hello Sriram,

    I'm sure many people have their own opinions as to what the "best" way is for consuming REST based web services. From a web client I prefer to use something like AngularJS which has the ability to easily wrap a RESTful service ( Link to docs). From a managed client you could use something like RestSharp which I have used in a few of our samples. Does that help answer your question?

    To answer your second question: Yes. You could expose a service method that obtains the tenant specific connection string to the database using TenantContext.Current.ConnectionString. I would just make sure that this string does not travel across the wire in plain text.

    Regards,

    Bryan

  • Avatar
    Sriram

    Hi Bryan,

    I guess the answers are spot-on, particularly the second one.  We will try using this from a custom reporting tool and let you know how it goes.  Thank you very much.

    Regards,

    Sriram

  • Avatar
    Vinay Siripurapu

    Where is the attached sample?