Design pattern for iPhone -> web service functionality? - iphone

I'm developing an app that will talk with a web service exposing multiple methods. I'm trying to figure out what the best pattern would be to centralize the access to the web service, give options for synchronous and asynchronous access, and return data to clients. Has anybody tackled this problem yet?
One class for all methods seems like it would centralize everything well, but I'm thinking it would get confusing to return data to the correct places, especially when dealing with multiple asynchronous calls. Another thought I had was a separate subclass for each method, with some sort of factory brokering access, but I'm thinking that might be overengineering the situation.
(note: not asking for what method calls to use/how to parse response/etc, looking for a high level design pattern solution to the general problem)

I recently came across the same problem. While I don't believe my solution to be optimal, it may help you out.
I created a web service manager and an endpoint protocol. Each object that implements the endpoint protocol is responsible for connecting to a web service endpoint(method), parsing the returned data, and notifying its delegate(usually the web service manager) of completion or any errors. I ended up creating an EndpointBase class that I use 99% of the time.
The web service manager is responsible for instantiating the endpoints as needed and invoking them. All of the calls happen asynchronously.
All in all it seems to work pretty well for me. I did end up with a situation in which one endpoint relied on the response of another (I used the command pattern there).
SDK Components that you'll want to look at are:
NSURLConnection
NSXMLParser

Factories? We don't need no stinkin' factories.
I've done this a few times, and I basically do what you're saying: one object that provides methods for all the web service calls, encapsulating the details of communicating with the service, handling connection issues, etc. In one app it was a singleton, because it needed to keep session state; in another app it was just a collection of static methods.
Along with some formatting of the response data, that's the entirety of its responsibility.
It's left up to the callers is whether the call is synchronous or asynchronous; the class itself is written synchronously, and a caller just uses it in a separate thread if necessary. Cocoa's performSelector... methods make that easy.

If REST is a good fit for your data interactions, then I would suggest the ObjectiveResource library . It's designed to work seamlessly with a Ruby on Rails app, but it basically speaks JSON or POX (plain old XML) over HTTP using rails ActiveResource conventions.
It's basically a set of categories on NSObject and some of the primitive object types that will let you make calls like [Dog findAllRemote] to return a list of Dog objects, or [myDog saveRemote] to send changes made to the myDog object back to the server.

Related

Is it good practice to ALWAYS use a REST API for Razor Page specific data

Imagine I have a Razor Page or such like. Imagine the data used by that Razor Page is not used by any other page at all. So the data retrieval is very specific to this page only.
Is it bad practice to just grab the data directly using a database connection from within that Razor Page local to the only place that data is to be used?
If so, why should I abstract the data away into a separate API that isn't re-used anywhere? Why is it good practice?
It seems to me, that REST APIs are sometimes used unnecessarily and for no good reason. As if because every example video shows data retrieval from REST APIs. Correct me if I am wrong.
If your application is purely a server-side app, there is no justification for creating RESTful API that serves up JSON for it. Those kinds of APIs are usually created for "external" consumers, by which I mean third parties or the browser (via JavaScript). They are commonly implemented for client side apps - single page apps typically like React, Angular or Blazor where JSON is the data format of choice for the browser.
As to whether you should open database connections in your PageModel class, that's another question. For simple apps, why not? But for apps that need unit testing, it's not a good idea. You will be unable to execute unit test against the PageModel class without hitting the database.
As a habit, I tend to put the code that connects to a database in a series of separate classes, each one having an interface, and then inject them into the PageModel via dependency injection. That way I can mock the service represented by the interface for unit testing.
You might want to implement services that generate data as JSON within a Razor Pages app if you have some functionality that depends on Ajax requests for data. For those, you could use Web API controllers, minimal request handlers or even named handler methods that return JsonResult objects in the PageModel classes. With all of those, you might still want to put the code that actually calls the database in a separate class that is injected into the handler.

Should RESTful service in Golang include Client interface?

If I develop Booking REST service in Golang (i.e., in package booking). Is it a "GO way" to create BookingClient interface (backed up by struct) with business operations allowed, so that clients of my restful service would use BookingClient (imported from package booking) instead of sending http requests directly?
In general, no – if you provide a client in a particular language it'd only be a convenience, so (some) users can use your API easier. This of course assumes your client is well designed. I wouldn't provide merely an interface in Go just to indicate a set of possible API calls. This would be beneficial to a very narrow range of audience, probably for people developing a client for your API themselves, in programming language which just happened to be the same as implementation of your server. And even then they might not really like the idea of using the interface (e.g. they might only need a specific set of methods).
If you want to provide a client for your API, go ahead, do it, but separate it from the actual server (different package, maybe even different repo). In general one develops APIs over HTTP to allow for wide range of clients to access it, which could be written in any language. Instead of providing some interfaces I would invest my time in writing a good documentation.
In my opinion the answer to your question, assuming there is no more context provided, should be no different if you asked yourself if you should provide a client in, say, Python. The whole situation might change though if, for example, your API is used internally by your company and you develop mainly in Go.
It's usually preferable to do this, and most companies do, but provide documentation for working directly with the API. The main use case for that is people working with different languages than the ones you intended.
You can have a look at a new RESTful framework I wrote, that includes infrastructure to automatically compile clients with Go templates, although I haven't gotten to writing a Go client compiler. If you want to write one it would be greatly appreciated :) https://github.com/EverythingMe/vertex
Testing is important in Go, so writing testable code is something you should do. If you use direct http requests you will have a harder time writing unit tests, compared to using a mocked struct.
Is there any reason to use a Client rather than calling the functions that call the REST endpoints? It's usually harder to mock a bigger thing, such as a Client struct, rather than a group of small functions.
You should put the client at booking.Client to avoid repeating yourself (booking.BookingClient) and maybe rename Client to something more descriptive.

iPhone + Web Services best practices

Accessing Web Services inside an iPhone app is a matter for which I did not find a clear, beautiful solution yet. I'm not talking about how to send queries or parse responses here, but about a "big picture" answer.
Disregarding the server-side technology, how do/would you plug your Model objects to your Web Service ? How do you design your proxy objects ? How do you cache your resources ?
If your web service happens to be a Ruby on Rails application, then Objective Resource is a great tool: http://iphoneonrails.com/.
If not, then what I tend to do is use ASIHTTPRequest (http://allseeing-i.com/ASIHTTPRequest/) which provides a nice network layer. Depending on the API, you might use ASI objects directly, or else you can subclass an existing ASI class if you want to add per-request functionality (such as authentication or response parsing).
You usually want to run requests in the background, so that the UI isn't blocked while waiting for the request to finish. You can always go the background thread route, but a nice "Objective C" style approach that ASIHTTPRequest provides is to instead provide a delegate which is called when the request finishes (see also "Creating an asynchronous request" at http://allseeing-i.com/ASIHTTPRequest/How-to-use). In many cases the request delegate is the view controller that initiates the request.
The model layer depends on the complexity, and also what format the data comes in. Most of the APIs I've worked with use JSON, for which you can use SBJSON or yajl-objc to parse. These usually give you the data parsed into base classes like NSString, NSArray and NSDictionary. Sometimes that's sufficient, or if you want your models to exist as their own classes, then you can have the models inherit from a base class that takes care of turning the NSDictionary/NSArray into properties.
Finally for caching, Core Data provides a good way to persist to disk. For caching in memory, you can have the requests occur in a separate "manager" class that is shared between controllers. These managers use the Singleton design pattern as described here: What should my Objective-C singleton look like?.

using REST webservices as a datasource for Lift?

Is there a way to use a webservice (REST in this case) as the data source for a Lift application? I can find a number of tutorials/examples of using Lift to provide the REST API, but in my case the data is hosted elsewhere and exported as a REST webservice. Pointers to doc are greatly appreciated.
Thanks,
Jeff
This is not related to Lift in fact. There is a lot of different pieces of information already:
HttpClient library as was suggested already,
or Dispatch Scala library for accessing HTTP services
information on how to cache data in Scala in various ways in case you need it
Think about caching thoroughly, it is generally a good choice if your application generates a lot of requests and you can afford caching. Caching will let you achieve many goals:
decrease response time, as you do not depend on the remote service (if you do synchronous data processing)
avoid Denial of Service in case the remote service dies. Otherwise your application will generate many sockets to read data and exhaust resources (either sockets or threads or something else)
do not exceed SLA of the remote service, as many services constrain the number of requests you are allowed to pefrorm per some unit of time.
So you can just sit and put these things together, that's it.
If you really want to be fancy, you can create a Record implementation for a REST-based data source. There's already one of these in existence that works with CouchDB. Using the lift-couchdb module, the interactions with CouchDB are abstracted away and all you deal with is the Scala code. There is a short wiki page with instructions on how to get started with lift-couchdb here:
http://www.assembla.com/wiki/show/liftweb/CouchDB
The pertinent source code files are available here:
http://github.com/lift/lift/tree/master/framework/lift-persistence/lift-couchdb/src/main/scala/net/liftweb/couchdb/
Using the Record interface gives you access to lots of Traits which you use to provide functionality with minimal code-writing such as creating HTML forms, providing lifecycle based calls, and easy hooks for validation.
I've put a scala layer over HttpClient and then use that. I've been meaning to put this on github for some time.
I use Dispatch (which is a wrapper around HttpClient) for making REST calls. Looks nice and simple

Using SOAP to expose CRUD operations

Is exposing CRUD operations through SOAP web services a bad idea? My instinct tells me that it is not least of which because the overhead of doing database calls overhead could be huge. I'm struggling to find documentation for/against this (anti)pattern so I was wondering if anyone could point me to some documentation or has an opinion on the matter.
Also, if anyone knows of best practises (and/or documentation to that effect) when designing soap services, that would be great.
Here's an example of how the web service would look:
Create
Delete
Execute
Fetch
Update
And here's what the implementation would look like:
[WebMethod]
public byte[] Fetch(byte[] requestData)
{
SelectRequest request = (SelectRequest)Deserialize(requestData);
DbManager crudManager = new DbManager();
object result = crudManager.Select(request.ObjectType, request.Criteria);
return Serialize(result);
}
If you want to use SOAP in a RESTful manner then there is a interesting standard for this, WS-Transfer; which provides loosely coupled CRUD endpoints; from which you inspect the message and act upon your entities accordingly.
Then you can layer whatever else you want on top, WS-Secure, WS-Reliable messaging and so on.
I think publishing a SOAP service that exposes CRUD operations to anonymous, public "users" would be a particularly bad idea. If, however, you can restrict one or both of these caveats, then I see nothing wrong with it (moreover I've implemented such services many times).
You can require, in addition to whatever method parameters your require to perform the operation, username & password parameters that in effect authenticates the originator prior to processing the request: a failure to authenticate can be signalled with the return of a SOAP exception. If you were especially paranoid, you could optionally run the service over SSL
You can have the server solution that deals with sending and receiving the requests filter based on IP, onyl allowing requests from a list of approved addresses.
Yes, there are overheads to running requests over SOAP (as opposed to exposing direct database access) - namely the processing time to wrap a request into a HTTP request, open a socket & send it (and the reverse at the receiving end and the again for the response) - but, it does have advantages.
Java (though the NetBeans IDE) and .Net (through VS), both support consumption of Web Services into projects / solutions - the biggest benefit of this is that objects / structures on the remote service are automatically translated into native objects in the consuming application, which is exceptionally handy.
If all you want to do is CRUD over the web, I'd look at some different technologies for doing REST instead of using WS*. SQL Data Services (formerly Project Astoria) might actually be a good alternative.
There is nothing wrong with exposing the CRUD operations via SOAP web-services per se.
You will obviously find quite a lot of examples for such services.
However depending on your particular requirements you might find that for you using SOAP is too much overhead or that you could be better off using use JSON/AJAX etc.
So I believe that unless you will provide additional details about your particular details there is no good answer for your question.