Today, let’s further enhance our simple Flight Service example that I have developed during my last two posts. One problem we have with our service is its service endpoint URL. If you could remember, last time we used a JSON specific request to test the service. Our service URL looked like the following.
But, if we want to test our service with an XML request then, we can’t use the above service endpoint since it is a JSON specific one. Therefore, we have to produce the XML specific URL using the operations’ XML request specifications.
Hence, our XML specific URL becomes the following.
Now, you get it! Our service URL differs based on the request format that we are willing to use. Isn’t it cool if we could define one service endpoint URL for all request formats? That is exactly what we are going to achieve today using the “Route” functionality of ServiceStack.
Remember, last time I mentioned you that ServiceStack is a very powerful tool that could be used to develop state of art REST APIs. The power of RESTful services hinges around the URL formats. Routes play a vital role when it comes to developing REST APIs using ServiceStack.
Now, let’s go ahead and add a route to our FlightRequest class (see below).
Remember, we add routes to request class not to service class. Hence, one service can have different service URLs that belong to different request types. In this example I have used the POST verb option for the route.
Now, press F5 to debug the service. If you go and inspect request details for JSON then, you’ll see that our newly defined route is available to use now.
Our service URL becomes much simpler too.
Let’s use this new service URL in REST Console tool to perform a JSON request. Fill in the required REST Console fields as shown below and press POST button.
Inspect the response and see that we have received our expected response in JSON format.
Don’t’ worry about the ArrivalTime and DepartureTime response values as those values are encoded in JASON date/time format which is not very readable.
Now, let’s use the same service URL against an XML request. We can use the sample XML given in XML request specification of the service operation to produce the XML request.
We have to change the request details in REST Console as shown below. Remember, to keep the Request URI unchanged. Press POST button.
Inspect the response and verify that we have received the expected response in XML format.
That’s it! We specified a RESTful URL using Routes in ServiceStack and tested it with JSON and XML request successfully.