what are the limitations of a .net web api service? - asp.net-web-api

I admit I am not wholly familiar with the .net webapi, but I have just been handed a project that a previous developer started and explained prior to his leaving that using the webapi services that we could instantiate a service that would continually compare file data with database data if one was newer than the other it would update either the database or the file. The trick is that their is a old PowerBuilder Com piece that extracts or compresses depending on whether it is going to the database or visa versa.
Additionally there will be real time requests for files (data) which will require those requests to be elevated in the process for being sent to the Com object as it were.
With this rather lengthy concept laid out, can a webapi service actually run as a continuous service as described? My understanding was or is that it cannot, and that a different service approach would be required using the webapi to manage the queues and messages for real time requests. Am I missing something here?
Thanks in advance.
Russ

WebApi is not a platform for continuous services. Its purpose is just to provide an interface to your application over HTTP.
In this scenario, WebApi would only be useful in its ability to accept requests. The data in the request can then be used to query your long running internal systems for data, or to update or create new data. WebApi embraces the HTTP verbs (GET, POST etc) for this exact purpose, making HTTP the protocol of your application's state.
Also, with regard to returning data. WebApi simplifies the serialization of a complex object into javascript (by default, overridable if need be). This is useful when your Api is consumed by clients speaking json.

Related

Replacing REST calls with GraphQL

I've recently read about the advantages (and disatvanteges) of GraphQL over Rest API.
I am developing a webpage that consumes several different Rest APIs and Soap services. Some of those services are dependent, meaning that a result from Rest1 will be passed as a parameter to Rest2 which will be passed to Soap service for a final return value.
From what I understood, GraphQL deals with multiple data sources and query nesting, but I have not yet understood if it will handle those nested dependent queries.
Can anyone that worked with several data sources that are dependent with GraphQL tell me if it can be done? My project should be up in 2 weeks and investing time in learning and setting up GraphQL and ending up not using it because it's not supporting my case would be a big failure for me.
Note: the APIs and services are not mine, I am consuming them from an outside source
I'm assuming you haven't yet setup a GraphQL server. Once you do, you can see how this isn't too difficult. So, I'd recommend you setup your own server first. The Egghead Course, "Build a GraphQL Server" got me started, but it's not free.
In essence, you'll be setting up your schema then defining how to resolve with data. When you resolve, you can setup an express server to query a database, or you can hit a REST interface, or hit your SOAP interface. How you retrieve the data is up to you, so long as you return it in compliance with your defined schema.
Hope that makes sense. Mocking up a mini app to demonstrate is possible, but since I don't have one handy, this is the best advice I can offer.

How do Web Applications communicate with a server?

Let's say I wanted to create a collaborative web application where users can simultaneously work on e.g. a diagram. I have my interactive web site (HTML/CSS/JavaScript) on the client side, and let's say a Java application synchronizing a centralized model on the server side. How would client and server exchange messages? To get a better idea of how the system is supposed to work like, here are some details and a small illustration:
Requirements
The underlaying technology should support authorized communication to show/hide sensitive information.
The model of the diagram should only exist on the server (centralized model, no copies), whereby changes should be broadcasted to other users (other browsers who are currently editing the same document).
After receiving changes to the model, the server shall perform computationally higher demanding tasks such as consistency checks and inform the user if e.g. an action is invalid.
Constraints
The system must not poll or set flags (it should be a direct communication).
The website must not be reloaded during use.
Software running on the client must be restricted to JavaScript.
Technology I've found
Here are some of the solutions I've looked at, ranked from (imho) most suitable to least, whereby I'm not sure if the list is even complete and all my assumptions are correct.
Java Web Service using javax.jws - The service would offer an API described by WSDL and be capable of responding with SOAP messages using the HTTP protocol, but can JavaScript process these messages?
Servlets & Java Server Pages (JSPs) - Would, as far as I know, require a page reload to fetch new content (isn't this pretty much the same as PHP? Both are executed on the server to generate HTML pages..)
I've already found this question which, however, does not provide concrete technologies in the answer. Thank you for any hints and clarification, I dearly appreciate it!
As you have already found out, there are many approaches to this common problem.
SOAP (sometimes called "Web Services" or "WS*") is a standard that was developed for application to application communication. It's strengths are precise specifications (and therefore many good libraries), interface sharing for client and server (through WSDL), and discoverability.
However, SOAP has very limited -if any- support in Browsers.
The most common modern approach is probably RESTful web services based on XML or JSON. When used in a browser as client, JSON is preferred, as the unmarshalling is trivial in JavaScript. Many frameworks and libraries like Angular and jQuery take on the tedious cross-browser AJAX request crafting. Some boilerplate is required to wrap the data in HTML, however. This downside can also be an upside if you consider the cleaner architecture and maintainability.
Since you're using Java on your server, you might also want to look into JSFs AJAX capabilities. It doesn't really use REST (no well-defined resources), but loads server-side rendered chunks of your HTML page asynchronously (read: AJAX) and re-renders them in the DOM. This can be seen as a compromise between real REST and full page reloading. The good side of it is you don't have to define any resources but your backing beans. The downsides are: possible overhead, since you're downloading HTML instead of pure data; and bad testability since you cannot access the rendered chunks outside the JSF context.
Wholly different issues are 1. the synchronization of concurrent requests and 2. communication with clients from server. For the latter you can either look into Web Sockets (the next big thing) or the good-old polling.
If concurrent edits of the same data are a concern to you, you'll have to implement a sort of strategy to tell whether edits can be merged or whether one has to be declined. The client will need to handle such situations and offer the user reviewing, overriding or reverting etc.
EDIT: more on Java servlets and JSP
Servlets are nothing but Java classes that handle specific HTTP requests, usually bound to certain URL paths. They're comparable to PHP pages: In PHP the web server gets a request and searches for a corresponding PHP file. Then it parses the PHP script and returns the response. Servlets do the same, only the syntax is very different. JSP is mostly a try at bringing more PHP-ish syntax to Java. Behind the curtains, they're rendered to pure Java servlets.
Java servlets have a long history which is older than AJAX, but many frameworks have taken on the challenge of implementing flexible resource handling on the server. Most notably Jersey and RESTEasy, which are implementations of the Java EE standard JAX-RS; and Spring, which is a request-based framework that competes well against Java EE standards. Then there is also JSF, which is sometimes called a successor of JSP. To the user it's little different than JSP, but the syntax is nicer and IMHO it is more feature-rich than JSP. Especially considering extensions like PrimeFaces. In contrast to JSP, JSF embraces AJAX and many built-in components are capable of communicating with the server using AJAX, including calling Java functions and re-rendering parts of the page.
I would recommend you try websockets since connections will be persistent between clients and server and any of them can send a message at any time.
You could implement a websocket server in Java on the server and use Javascript's built in websockets functionallity on the clients.
Take a look at https://www.websocket.org/ to learn more about websockets.

Keep state between webapi calls

I need to send an information to a user via a web-api only once by session, and I used to do in asmx by storing a variable in the session.
As in web-api I can't use sessions, how can I do this ?
Started as a comment, but ended up being too long...
ASP.NET Web API is mainly used to create HTTP services and, as Microsoft claim, ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. Such services are meant to be stateless so what you're trying to do is technically going against a pretty fundamental design goal. Having said that, things are not as clear-cut as they seem and there's some (almost religious) debate over whether a REST service should be stateless or allow state in some degree.
The following SO questions might give you some help and/or direction about achieving what you want:
ASP.NET Web API session or something?
If REST applications are supposed to be stateless, how do you manage sessions?
How to manage state in REST
Also, the following StrathWeb article gives some additional advice (with a code example) and links to other sources of information:
http://www.strathweb.com/2012/11/adding-session-support-to-asp-net-web-api/
In a project I'm currently working on, I'm having to store some state information for token-based user authentication and, since I have access to a database, I use a table to store the information I need. Technically speaking, and certainly for some people, I'm breaking the rules. But it works for me and, at the end of the day, you have a job to do and you may not always have the time to do things 100% correctly, so you have to be pragmatic in your approach.

REST in workflow applications - where to keep the state?

I tried to take a more detailed look at REST - Spring seems to love it so much, and I am confused. REST is fine for basic CRUD operations on "resources", but it seems awkward for applications which need to keep state, such as workflow applications. I read in one of the answers on SO, can't find it now, that the state should be kept on the client. This seems strange: what prevents then the client from cooking up a request, claiming he is in a state which he is not in? A way around this could be that the server sends to the client his next state signed, and the client then uses this signed state on his next request to the server. If anyone has seen a "RESTful workflow application", is this how things actually get done?
REST = Representational STATE Transfer. Client and server exchange the state of a resource. So basically it's kept on the server and updated (/created/deleted) by the client.
REST isn't awkward at all for workflow applications, however you may define that. The most difficult part when designing REST applications is designing the representations and most of all the resources. A resource isn't merely an entity from the database.
As #NeilMcGuigan has mentioned, the RestBucks sample application deals with workflows. There's a video on the SpringSourceDev Channel on YouTube, where Oliver Gierke presents the application.

Should I build a REST backend for GWT application

I am planning a new application and have been experimenting with GWT as a possible frontend. The design question I am facing is this.
Should I use
Option A: GWT-RPC and build the app quickly
Option B: Build a REST backend using Spring MVC 3.0 with all the great #Controller, #Service, #Repository annotations and build a client side library to talk to the backend using the GWT overlay features and the GWT Request builder?
I am interested in all the pros and cons and people experiences with this type of design?
Ask yourself the question: "Will I need to reuse the server-side interface with a non-GWT front-end?"
If the answer is "no, I'll just have a GWT client": You can use GWT-RPC, and take advantage of the fact that you can use your Java objects both on the server and the client-side. This can also make the communication a bit more efficient, at least when used with <inherits name="com.google.gwt.user.RemoteServiceObfuscateTypeNames" />, which shortens the type names to small numeric values. You'll also get the advantage of better error handling (using Exceptions), type safety, etc.
If the answer is "yes, I'll make my service accessible for multiple kinds of front-ends": You can use REST with JSON (or XML), which can also be understood by non-GWT clients. In addition to switching clients, this would also allow you to switch to a different server implementation (maybe non-Java) in the future more easily. The disadvantage is, that you'll probably have to write wrappers (JavaScript Overlay Types) or transformation code on the GWT client side to build nice Java objects from the JSON objects. You'll have to be especially careful when you deploy a new version of the service, which brings us back to the lack of type safety.
The third option of course would be to build both. I'd choose this option, if the public REST interface should be different from the GWT-RPC interface anyway - maybe providing just a subset of easy to use services.
You can do both if use also use the RestyGWT project. It will make calling REST based JSON resources as easy as using GWT-RPC. Plus you can typically reuse the same request response DTOs from the server side on the client side.
We ran into the same issue when we created the Spiffy UI Framework. We chose REST and I would never go back. I'd even say GWT-RPC is a GWT Anti-pattern.
REST is a good idea even if you never intend to expose your REST endpoints. Creating a REST API will make your UI faster, your API better, and your entire application more maintainable.
I would say build a REST backend. In my last project we started by developing using GWT-RPC for the first few months, we wanted fast bootstrapping. Later on, when we needed the REST API, it was so expensive to do the refactoring we ended up with two backend APIs (REST and RPC)
If you build a proper REST backend, and a deserialization infra on the client side (to transform the json\xml to GWT Java objects) then the benefit of the RPC is almost nothing.
Another sometimes forgotten advantage of the REST approach is that it's more natural to the browser running the client, RPC is a propitiatory protocol, where all the requests are using POST. You can benefit from client side caching when reading resources in the standard way.
Answering ams comments:
Regarding the RPC protocol, last time I "sniffed" it using firebug it didn't look like json, so I don't know about that. Though, even if it is json based, it still uses only the HTTP POST method to communicate with the server, so my point here about caching is still valid, the browser won't cache POST requests.
Regarding the retrospective and what could have done better, writing the RPC service in a resource oriented architecture could lead later to easier porting to REST. remember that in REST one usually exposes resources with the basic CRUD operations, if you focus on that approach when writing the RPC service then you should be fine.
The REST architectural style promotes inspectable messages (which aids debugging and security), API evolution, multiple platforms, simple interfaces, failure recovery, high scalability, and (optionally) extensible systems via code on demand. It trades per-interaction performance for overall network efficiency. It reduces the server's control over consistent application behavior.
The "RPC style" (as we speak of it in opposition to REST) promotes platform uniformity, interface variability, code generation (and thereby the ability to pretend the network doesn't exist, but see the Fallacies), and customized interactions. It trades overall network efficiency for high per-interaction performance. It increases the server's control over consistent application behavior.
If your application desires the former qualities, use the REST style. If it desires the latter, use the RPC style.
If you're planning on using using Hibernate/JPA on the server-side and sending the resulting POJO's with relational data in them to the client (ie. an Employee object with a collection of Phones), definitely go with the REST implementation.
I started my GWT project a month ago using GWT RPC. All was well until I tried to serialize an object from the underlying db with a One-To-Many relationship in it. And got the dreaded:
com.google.gwt.user.client.rpc.SerializationException: Type 'org.hibernate.collection.PersistentList' was not included in the set of types which can be serialized by this SerializationPolicy
If you encounter this and want to stay with GWT RPC you will have to use something like:
GWT Request Factory (www.gwtproject.org/doc/latest/DevGuideRequestFactory.html) - which forces you to write 3+ classes/interfaces per POJO you want to share with the client. OUCH!
Gilead (sourceforge.net/projects/gilead/) - which appears to a dead project.
I'm now using RestyGWT. The switch was fairly painless and my POJO's serialize without issue.
I would say that this depends on the scope of your total application. If your backend should be used by other clients, needs to be extendable etc. then create a separate module using REST. If the backend is to be used by only this client, then go for the GWT-RPC solution.

Resources