good practice: REST API as the interface between the interface layer and business layer? - api

I was thinking about the architecture of a web application that I am planning on building and I found myself thinking a lot about a core part of the application. Since I will want to create, for example, an android application to access it, I was already thinking about having an API.
Given the fact that I will want to have an external API to my application from day one, is it a good idea to use that API as an interface between the interface layer (web) and the business layer of my application? This means that even the main interface of my application would access the data through the API. What are the downsides of this approach? performance?
In more general terms, if one is building a web application that is likely to need to be accessed in different ways, is it a good architectural design to have an API (web service) as the interface between the interface layer and business layer? Is REST a good "tool" for that?

Sounds like you've got two questions there, so my answer is in two parts.
Firstly, should you use an API between the interface layer and the business layer? This is certainly a valid approach, one that I'm using in my current project, but you'll have to decide on the benefits yourself, because only you know your project. Possibly the largest factor to consider is whether there will be enough different clients accessing the business layer to justify the extra development effort in developing an API? Often that simply means more than 1 client, as the benefits of having an API will be evident when you come to release changes or bug fixes. Also consider the added complexity, the extra code maintenance overhead and any benefits that might come from separating the interface and business layers such as increased testability.
Secondly, if you implement an API, should you use REST? REST is an architecture, which says as much about how the remainder of your application is developed as it does the API. It's no good defining resources at the API level that don't translate to the Business Layer. Rest tends to be a good approach when you want lots of people to be able to develop against your API (like NetFlix for example). In the case of my current project, we've gone for XML over HTTP, because we don't need the benefits that Rest generally offers (or SOAP for that matter).
In general, the rule of thumb is to implement the simplest solution that works, and without coding yourself into a corner, develop for today's requirements, not tomorrow's.
Chris

You will definitely need need a Web Service layer if you're going to be accessing it from a native client over the Internet.
There are obviously many approaches and solutions to achieve this however I consider the correct architectural guideline to follow is to have a well-defined Service Interface on the Server which is accessed by the Gateway on the client. You would then use POCO DTO's (Plain old DTO's) to communicate between the endpoints. The DTO's main purpose is to provide optimal representation of your web service over the wire, it also allows you to avoid having to deal with serialization as it should be handled transparently by the Client Gateway and Service Interface libraries.
It really depends on how to big your project / app is whether or not you want want to go through the effort to mapping your DTO's to the client and server domain models. For large applications the general approach would be on the client to map your DTO's to your UI Models and have your UI Views bind to that. On the server you would map your DTO's to your domain models and depending on the implementation of the service persist that.
REST is an architectural pattern which for small projects I consider an additional overhead/complexity as it is not as good programattic fit compared to RPC / Document Centric web services. In not so many words the general idea of REST is to develop your services around resources. These resources can have multiple representations which your web service should provide depending on the preferred Content-Type indicated by your HTTP Client (i.e. in the HTTP ACCEPT HEADER). The canonical urls for your web services should also be logically formed (e.g. /customers/reports/1 as opposed to /GetCustomerReports?Id=1) and your web services would ideally return the list of 'valid states your client can enter' with each response. Basically REST is a nice approach promoting a loosely-coupled architecture and re-use however requires more effort to 'adhere' to than standard RPC/Document based web services whose benefits are unlikely to be visible in small projects.
If you're still evaluating what web service technology you should use, you may want to consider using my open source web framework as it is optimized for this task. The DTO's that you use to define your web services interface with can be re-used on the client (which is not normally the case) to provide a strongly-typed interface where all the serialization is taken for you. It also has the added benefit of enabling each web service you create to be called by SOAP 1.1/1.2, XML and JSON web services automatically without any extra configuration so you can choose the most optimal end point for every client scenario, i.e. Native Desktop or Web App, etc.

My recent preference, which is based on J2EE6, is to implement the business logic in session beans and then add SOAP and RESTful web services as needed. It's very simple to add the glue to implement the web services around those session beans. That way I can provide the service that makes the most sense for a particular user application.

We've had good luck doing something like this on a project. Our web services mainly do standard content management, with a high proportion of reads (GET) to writes (PUT, POST, DELETE). So if your logic layer is similar, this is a very reasonable approach to consider.
In one case, we have a video player app on Android (Motorola Droid, Droid 2, Droid X, ...) which is supported by a set of REST web services off in the cloud. These expose a catalog of video on demand content, enable video session setup and tear-down, handle bookmarking, and so on. REST worked out very well for this.
For us one of the key advantages of REST is scalability: since RESTful GET responses may be cached in the HTTP infrastructure, many more clients can be served from the same web application.
But REST doesn't seem to fit some kinds of business logic very well. For instance in one case I wrapped a daily maintenance operation behind a web service API. It wasn't obvious what verb to use, since this operation read data from a remote source, used it to do a lot of creates and updates to a local database, then did deletes of old data, then went off and told an external system to do stuff. So I settled on making this a POST, making this part of the API non-RESTful. Even so, by having a web services layer on top of this operation, we can run the daily script on a timer, run it in response to some external event, and/or have it run as part of a higher level workflow.
Since you're using Android, take a look at the Java Restlet Framework. There's a Restlet edition supporting Android. The director of engineering at Overstock.com raved about it to me a few years ago, and everything he told us was true, it's a phenomenally well-done framework that makes things easy.

Sure, REST could be used for that. But first ask yourself, does it make sense? REST is a tool like any other, and while a good one, not always the best hammer for every nail. The advantage of building this interface RESTfully is that, IMO, it will make it easier in the future to create other uses for this data - maybe something you haven't thought of yet. If you decide to go with a REST API your next question is, what language will it speak? I've found AtomPub to be a great way for processes/applications to exchange info - and it's very extensible so you can add a lot of custom metadata and yet still be eaily parsed with any Atom libraries. Microsoft uses AtomPub in it's cloud [Azure] platform to talk between the data producers and consumers. Just a thought.

Related

Existing SOAP service and new Angular Web App

We have an established WCF SOAP service. Its interface is defined in WSDL, from which C# classes are generated for our server (customers generate client-side bindings in various languages, from the same WSDL). The WSDL has a current version, which we can change a bit, and old versions, which we can't change or drop without a deprecation period, consultation etc. The SOAP requests tend to be complicated, having multiple XML namespaces within the same request.
The WCF SOAP service has a lot of "smarts" in it, and provides exactly the kinds of fetching and reporting facilities that we need for a new Web application that we need to make. We hope to use AngularJS for the client side of that. But these complex SOAP requests aren't easy to make in JavaScript world. If only we had a REST service, we could use angular Resource service. If not that, then a server that spoke JSON, albeit in an RPC style like SOAP, would run a fairly close second.
I've had various ideas for how the impedance mismatch between our server and client might be mitigated. But nothing sounds quick or easy.
I've thought of: -
Write a new REST service. Exactly what the client-side wants, but a serious piece of new development.
WebHttpBinding looks to offer something. But seems to me like it requires C# markup of custom attribute (how to achieve when our C# is generated from WSDL) and possibly wouldn't support our complex types
Obtain or write loads of client-side JS to abstract away calling SOAP services. But, unless this can be auto-generated from the WSDL, it's a huge amount of client-side code to write.
Write an IDispatchMessageFormatter for the server, to accept some JSON format of messages that I invent. Sounds hard, especially as good examples of people implementing and integrating IDispatchMessageFormatter seem hard to come by.
Write a MessageEncoder to swap between JSON and XML. But this isn't really an encoding operation, as became very clear when I tried to write it!
I'm searching for suggestions.
Generally, I recommend a REST service for any AngularJS development and have wrapped a number of legacy systems with Node.js API servers. Of course there is a massive amount of "it depends", but generally most projects will be happier and more productive following that route.
Some Things To Think About
How well does your current SOAP API fit the user interface requirements?
Are you experienced with Express, Sinatra, Flask or other micro-framework that allow rapid development of REST APIs? I find I can build a solid Node.js Express API server in a couple of hours and then extend it as I build the AngularJS application out.
How experienced are you with AngularJS? It's a more advanced project to build a complex data layer client-side.
Six Reasons Why REST is Important for AngularJS
It's much faster to write Angular code using $resource and $http. Get the API right is a good recommendation for effective AngularJS development. Indeed, you could argue that AngularJS is designed for REST, and that's why plain JavaScript works for the model (see 2).
Angular's plain-old JavaScript object data model works well with a REST API that speaks JSON that matches the user interface. However, issues arise when there isn't a good fit- Angular doesn't have a formal data model so you end up writing an lot of code trying to rationalize your API to work well with Angular. 3rd party libraries like breeze.js may offer some solution, but it's still awkward.
You can scale easily with caching. It's easy to add Redis or memcache or Varnish or other common HTTP caching solutions into the mix. Resource-based abstractions are perfect for caching strategies due to the transparency and idempotency of a REST api.
Loose coupling of front-end and server- it will be easier to support changes to the backend if you migrate off SOAP or need to integrate with other services.
It's generally easier to test JSON APIs separately from AngularJS logic, so your test suites will be simpler and more effective.
Your new REST API will be easier to leverage for future AngularJS and JSON-oriented projects.
I hope that helps.
Cheers,
Nick

Moving MVC-style service layer under WCF

Recently I've been working with MVC4 and have grown quite comfortable with the View > View Model > Controller > Service > Repository stack with IoC and all. I like this. It works well. However, we're moving towards company wide application platform that will serve the majority of all business applications needs within the company.
Basic architecture goals:
Client facing MVC site
Internal Admin web site
Plethora of scheduled jobs importing/exporting data/etc to third parties
Service Bus sitting in the middle to expose business events
Public API for customer consumption
My initial thoughts are to introduce an "enterprise service layer" by applying my service interfaces to WCF contracts and registering the WCF proxy classes in my IoC. This would allow me to reuse the same pattern I'm currently using, butt I've not found a lot of examples of this in practice. Except this guy.
Admittedly though, I'm unsure what the best solution is for a project this scale.
1) What are the considerations when centralizing business services?
2) How does this affect cross cutting concerns like validation, authorization, etc? I thought I had that figured out already, but putting DTOs between the layers changes all this.
3) I'm experienced with WCF, but I hear Service Stack is all the rage...Should SS be a consideration with its RESTful goodness?
This guy here. I am not an expert in this area by any means, but hopefully I can provide a bit more context around things.
The main problem with using IoC to resolve WCF ChanelFactory dependencies as per my post is that the client also needs to have access to the service contracts. This is fine for a View > View Model > Controller > Service > Repository type architecture but is not likely to be possible (or desirable) for a shared public API.
In an attempt to cover your other questions:
1) Some of the concerns are already mentioned in your second question. Add to that things like security, discoverability, payload type (XML, JSON etc), versioning, ... The list goes on. As soon as you centralize you suddenly gain a lot more management overhead. You cannot just change a contract without understanding the consequences.
2) All the cross cutting stuff needs to be catered for in your services. You cannot trust anything that comes in from clients, especially if they are public. Clients can add some validation for themselves but you have to ensure that your services are locked down correctly.
3) WCF is an option, especially if your organisation has a lot of existing WCF. It is particularly useful in that it supports a lot of different binding types and so means you can migrate to a new architecture over time by changing the binding types of the contracts.
It is quite 'enterprisey' and has a bewildering set of features that might be overkill for what you need.
ReST is certainly popular at the moment. I have not used Service Stack but have had good results with Asp.Net Web Api. As an aside, WCF can also do ReST.
I've previously provided a detailed explanation of the technical and philosophical differences between ServiceStack and WCF on InfoQ. In terms of API Design, this earlier answer shows the differences between ServiceStack Message-based approach and WCF / WebApi remote method approach.
SOAP Support
ServiceStack also has Soap Support but you really shouldn't be using SOAP for greenfield web services today.
HTML, Razor, Markdown and MVC
ServiceStack also has a great HTML Story which can run on stand-alone own with Razor support as seen in razor.servicestack.net or Markdown Razor support as seen in servicestack.net/docs/.
ServiceStack also integrates well with ASP.NET MVC as seen in Social Bootstrap Api, which is also able to take advantage of ServiceStack's quality alternative components.

difference between WCF Services and Web Services and REST Service

What is the difference between WCF Services and Web Services in .netWhen should I use WCF and when to use Web Services.Is REST and WCF service the same? Thanks
Web Service is an abstract term encompassing a large variety of data providers for distributed systems. Perhaps you are referring to ASMX web services, which can still be found in the wild but aren't really widely used in new development these days.
WCF Service is Microsoft's implementation of SOAP. There are others implementations or you could roll your own (not recommended).
SOAP is a kind of stateful, session-based, message-based web service. It's good if your service is designed as a set of complex actions.
REST is a stateless, sessionless, resource-based web service. It's good if your service is designed to access data and perform simple CRUD operations on it. SOAP and REST are mutually exclusive. A service cannot be both. There are ways to manipulate vanilla WCF to make is RESTful but these techniques are becoming deprecated. If you want to implement a RESTful web service there are two main choices in the Microsoft world: WCF Data Services and ASP.NET Web API.
REST is an architecture
WCF is a API in .NET Framework to build connected service oriented application.
In olden days a functionality developed as Web Service was accessible via internet and the same to be available on local network was available via Remoting.
Using WCF we don't need to develop different code for it to be accessible over internet and on local network. Just configuring it with bindings would be enough.
That is a very wide question...I am going to just give a brief high-level answer and suggest that you do some more searching as there are is already a lot written on each subject. But, hopefully this should give you a push in the right direction.
First, typically when people refer to WCF Services and Web Services, they are referring to the newer WCF conventions that make service calls fairly generic (they can be SOAP, REST, etc) and the old .asmx SOAP method of Web Services. So, along these lines, I would suggest looking more into WCF and SOAP/.ASMX for the difference of WCF and older Web Services.
As to WCF and REST, they are not the same. REST is more of an architecture, whereas WCF is a framework. As I already mentioned, WCF can be used to make SOAP calls or REST calls. I am not sure I can add much more without going into greater detail.
I will see if I can find some good articles on REST and WCF a little later, though. Personally, I do not see a reason to even pursue very far into the older way of calling web services (.ASMX pages) as WCF has pretty much made that obsolete. However, learning many different ways to skin a cat can be useful in an endeavor to find what fits you best.
Again, this is VERY high level, but these are very general topics with a lot surrounding each, so hopefully a high level overview will help direct you in studying deeper on each subject.
Some people mean "ASMX" when they say "Web Services".
Others just use "Web Services" to mean the generic technology, and consider WCF to be the current way to create Web Services on the .NET platform. The other kind are "ASMX Web Services", as distinguished from "WCF Web Services".
The "other kind" are a legacy technology, supported only for backwards compatibility. They should not be used for new development, so there's no point in you learning about them.
As others have stated, "REST" is an architecture style, not a technology.
WCF is multifaceted, so I'm going to speak of it with respect to its most common usage. The general difference between WCF and REST services is centered around the content. A REST call is usually more message/document/entity centered (With customer entities, find those starting with M; With order entities, get order 12 and is tied to the HTTP protocol. WCF tends to be more operation centered (Invoke find operation with params, Invoke get operation with parameters). WCF also isn't tied to HTTP.
FYI, there are extensions to create REST based services using WCF (WebInvoke, WebGet attributes).
Wcf:wcf is a technology as part of .net framework which provides environment to work with different distributed technologies an by following unified programming model.
wcf create a proxy.
wcf support data contract serializer.
records shown xml format.
**Rest:**Rest is an architectural style.which says use the existing features of the web in more effective,efficiency and simple manner.verbs like insert,update and delete.
Rest cannot create a proxy.
rest records shown jason format.
Web Service:a service which is hosted on website is called as webservice.
web service support xmlserializer
I see this is quite an old thread, but I have asked a similar question recently.
The answers given have all similar relevance, but in my opinion Ray was the closest to what was actually asked.
When designing or refactoring a web based solution, you always get the question should we go with SOAP or REST. The answer lies in the complexity of the business logic required behind the service. REST is good for simplistic API calls that usually contains small sets of requested data or over night processing with large sets, but mainly for data requests. SOAP is more of an interactive day to day service with business logic as well. For example many methods with plenty of parameters.
What we do as part of our web based solution, is to try and make use of both. For internal methods and primary functionalities we use SOAP, but for exposed APIs we prefer REST.
Framework related, definitely WCF as preferred choice, irrespective if SOAP or REST.

When should i choose to use WCF versus WCF Data Services

Assume a situation where a data will never be queried directly. AKA, there will always be some filtering logic and/or business logic that must occur.
When is a good reason to use data services outside of ajax/js?
Please don't site this page http://msdn.microsoft.com/en-us/data/bb931106.aspx
Your essentially asking what layer of abstraction should I use, WCF Data Services is built on top of WCF and aims to simplify the process of creating a REST based service that is consumable by anything on the web. It takes away a lot of the plumbing and configuration required to do this with a standard WCF service. The querying feature is another big plus and something that is difficult to get right with standard WCF.
So in short:
If you want to quickly build a loosely typed service that wraps an existing data model and enables querying support give WCF Data Services a go.
If you want full control over the service contract or the flexibility of exposing the service over any protocol, stick with plain old WCF.

Where WCF and ADO.Net Data services stand?

I am bit confused about ADO.Net Data Services.
Is it just meant for creating RESTful web services? I know WCF started in the SOAP world but now I hear it has good support for REST. Same goes for ADO.Net data services where you can make it work in an RPC model if you cannot look at everything from a resource oriented view.
At least from the demos I saw recently, it looks like ADO.Net Data Services is built on WCF stack on the server. Please correct me if I am wrong.
I am not intending to start a REST vs SOAP debate but I guess things are not that crystal clear anymore.
Any suggestions or guidelines on what to use where?
In my view ADO.Net data services is for creating restful services that are closely aligned with your domain model, that is the models themselves are published rather then say some form of DTO etc.
Using it for RPC style services seems like a bad fit, though unfortunately even some very basic features like being able to perform a filtered counts etc. aren't available which often means you'll end up using some RPC just to meet the requirements of your customers i.e. so you can display a paged grid etc.
WCF 3.5 pre-SP1 was a fairly weak RESTful platform, with SP1 things have improved in both Uri templates and with the availability of ATOMPub support, such that it's becoming more capable, but they don't really provide any elegant solution for supporting say JSON, XML, ATOM or even something more esoteric like payload like CSV simultaneously, short of having to make use of URL rewriting and different extension, method name munging etc. - rather then just selecting a serializer/deserializer based on the headers of the request.
With WCF it's still difficult to create services that work in a more a natural restful manor i.e. where resources include urls, and you can transition state by navigating through them - it's a little clunky - ADO.Net data services does this quite well with it's AtomPub support though.
My recommendation would be use web services where they're naturally are services and strong service boundaries being enforced, use ADO.Net Data services for rich web-style clients (websites, ajax, silverlight) where the composability of the url queries can save a lot of plumbing and your domain model is pretty basic... and roll your own REST layer (perhaps using an MVC framework as a starting point) if you need complete control over the information i.e. if you're publishing an API for other developers to consume on a social platform etc.
My 2ΓΈ worth!
Using WCF's rest binding is very valid when working with code that doesn't interact with a database at all. The HTTP verbs don't always have to go against a data provider.
Actually, there are options to filter and skip to get the page like feature among others.
See here: