Resource or Restlet - restlet

I am using Restlet 2.2.1 and building Rest services. As you know, Router is used to attach either Restlet or Resource as target.
Router router = new Router( getContext() );
router.attach("/healthcheck1",HealthCheckResource.class );
router.attach("/healthcheck2", new HealthCheckRestlet() );
Then you can implement your logic in handle()
Wondering which is best one to use? I know Resource has a very definite life cycle (doInit, handle, release ...) and good place to implement one time logic like initialization.

Attach a ServerResource subclass rather than a Restlet instance when feasible, for a couple of reasons:
Resources are the natural way to structure RESTful APIs. When you use the #Get, #Put, etc. annotations on a resource class, you're effectively documenting that part of your RESTful API, and there are tools that can extract that information to create online documentation automatically. If you use a Restlet instance, its behavior in response to GET, PUT, etc. is not immediately apparent. Ironically, using a Restlet makes it easier to write APIs that are not RESTful.
A separate instance of the resource class is created for each request, meaning that an instance is normally confined to a single thread, which simplifies reasoning about thread-safety. In constrast, the same Restlet instance will be used for all handle(...) calls, potentially leading to complicated thread-safety requirements.
Because each request gets its own resource instance, the resource methods might need to appeal to internal services that are passed via the application context or injected into the resource (see this Restlet extension).
Incidentally, your comment about "one time logic like initialization" might be a misunderstanding. The doInit method is called for each instantiated resource (i.e., once per request for that resource), not one time only.
Note that I'm recommending against directly subclassing Restlet as an end target for a resource URL, except maybe for trivial resources. Using subclasses of Restlet is a different matter: Attaching a Filter which wraps a resource is fine.

Related

What is the HTTP method for an API that calls another API?

I am writing a service where the client makes an API call to my service, and my service then augments the request payload, then passes it on to another service. For my API, what should the HTTP method be if it's not interacting with a database?
what should the HTTP method be
Key idea: the fact that your server communicates with another API, rather than a database, or a filesystem, is an implementation detail; details of your implementation are not supposed to be leaking into your messages.
Given that the incoming request has a message body; GET, HEAD, DELETE are all right out, because those methods have no defined semantics for a payload.
POST/PUT/PATCH are all possible.
Ideally, you would match the method token that you are using to talk to your back end. This is essentially how a reverse proxy works. You're just playing man in the middle, after all, so it shouldn't be too much of a surprise that the request semantics match.
They don't always, of course - and you might want to inject your own semantics if you find that the API you are calling has made poor method choices in its own design.
When in doubt, it is okay to use POST
One of the REST principles — namely, ‘Layered System’ constraint — implies that:
each component cannot "see" beyond the immediate layer with which they are interacting
So you actually should not make any difference between ‘simple’ and ‘proxied’ API calls.

Is there any issue will rise if am going to use post HTTP method for all CRUD operations

Is there any issue will rise if am going to use post method for all CRUD operations in Akka HTTP services. why we need to use separate HTTP method for CRUD operations.
There will not be any "issues" (e.g. failures, exceptions, etc.) that will arise within akka-http if you restrict all http methods to be POST. However, it does violate the definition of RESTful services.
Also, you do give up a useful organization technique. If you organize all read paths inside of GET and all write paths inside of POST, then you can add things like access control (read-only vs. read-write) at the method level.
You therefore lose a level of abstraction for no obvious reason except simplicity.

What is the difference between a cornice.Service and cornice.resource in Cornice?

I have read through the documentation many times over and search all over for the answer to this question but have come up short. Specifically I've looked at Defining the service and the Cornice API for a service and at Defining resource for resource.
I'm currently building a REST API that will have a similar structure to this:
GET /clients # Gets a list of clients
GET /clients/{id} # Gets a specific client
GET /clients/{id}/users # Gets a specific clients users
What would be the best way to go about this? Should I use a service or a resource or both? And, if both, how?
Resources are high-level convenience, services offer lower level control.
I am just learning cornice myself. Looking at the source code, a Resource creates Services internally, one for the item and one for the collection (if a collection path is specified). The resource also adds views to the services for each method defined with an http verb as the name or in the form collection_[verb].
So there is little difference except that resources are a neat, structured way to define services.
The resource decorator uses a url for the collection, as well as a url pattern for an object.
collection_path=/rest/users
path=/rest/users/{id}
The resource decorator is best used in view classes where you can use get/put/post/delete methods on the objects, as well as collection_get, collection_put, etc. on the collection. I have some examples here:
https://github.com/umeboshi2/trumpet/blob/master/trumpet/views/rest/users.py
Since I make heavy use of the resource decorator and view classes, I haven't found a need for the service function, but it allows you to create get,put,post decorators that wrap view callable functions.
If you are using backbone.js on the client side, the resource decorator and url examples work well with the Backbone collections and models.

developing your own RESTful API

in developing your own RESTful API. does it necessarilly needed to use the four different http methods? GET POST PUT & DELETE?
i was checking the Twitter REST API and saw that they are just using the common methods (GET & POST)
Short answer: No
Long Answer:
REST is not specific to any one protocol, instead it is a style of programming. This is helpful to keep in mind because a RESTful endpoint should be thought of as having specific goals. Your job is to expose the web service in the most RESTful way possible.
When you're making a RESTful API you are not required to use any specific HTTP methods. Instead, REST can be embodied in this guiding principal: That you must expose individually identifiable resources; these resources must be manipulable in their exposed form. Oh and use self descriptive messages.
I'm sure this is a leaky explanation. Try to see, though, that REST becomes much more clear when you have the key idea in mind. RESTful practices expose resources in a way that allows us work with state in a sane manner. The technical details of how to implement a RESTful API can be learned by reading this:
http://en.wikipedia.org/wiki/Representational_state_transfer
After that, read something specific to your language. Fast track: find some RESTful API written in your language and clone it/play with it.
You should use whatever HTTP methods are appropriate for the operations you expose.
For example, you should accept HTTP DELETE requests only for operations that delete things.
If your API does not allow callers to delete things (eg, a traffic or weather API), you should not accept the DELETE verb.
Only if you are going to support those logical operations:
GET - fetch a resource
PUT - update (or create) a resource
DELETE - delete a resource
POST - several uses: create a new resource in a collection, perform some operation that will alter a resource in some one (as opposed to PUTting an entirely new version of a resource)
Most APIs will want to to provide those operations, and will use all those methods. And don't forget HEAD - fetch information about a resource (but not the resource itself).

Passing client context using Unity in WCF service application

I have a WCF service application (actually, it uses WCF Web API preview 5) that intercepts each request and extracts several header values passed from the client. The idea is that the 'interceptor' will extract these values and setup a ClientContext object that is then globally available within the application for the duration of the request. The server is stateless, so the context is per-call.
My problem is that the application uses IoC (Unity) for dependency injection so there is no use of singleton's, etc. Any class that needs to use the context receives it via DI.
So, how do I 'dynamically' create a new context object for each request and make sure that it is used by the container for the duration of that request? I also need to be sure that it is completely thread-safe in that each request is truly using the correct instance.
UPDATE
So I realize as I look into the suggestions below that part of my problem is encapsulation. The idea is that the interface used for the context (IClientContext) contains only read-only properties so that the rest of the application code doesn't have the ability to make changes. (And in a team development environment, if the code allows it, someone will inevitably do it.)
As a result, in my message handler that intercepts the request, I can get an instance of the type implementing the interface from the container but I can't make use of it. I still want to only expose a read-only interface to all other code but need a way to set the property values. Any ideas?
I'm considering implementing two interfaces, one that provides read-only access and one that allows me to initialize the instance. Or casting the resolved object to a type that allows me to set the values. Unfortunately, this isn't fool-proof either but unless someone has a better idea, it might be the best I can do.
Read Andrew Oakley's Blog on WCF specific lifetime managers. He creates a UnityOperationContextLifetimeManager:
we came up with the idea to build a Unity lifetime manager tied to
WCF's OperationContext. That way, our container objects would live
only for the lifetime of the request...
Configure your context class with that lifetime manager and then just resolve it. It should give you an "operation singleton".
Sounds like you need a Unity LifetimeManager. See this SO question or this MSDN article.