I am looking to develop a Spring MVC Integration with HATEOAS. I've searched the web and I didn't find any such working example through which I can understand HATEOAS concept.
I only found this resource which itself has lots of code and is really difficult to understand. Is a complete working sample available?
You may have a look at this sample Spring/Boot HATEOAS project: https://github.com/opencredo/spring-hateoas-sample and some explanation in the related blog post: Implementing HAL hypermedia REST API using Spring HATEOAS
The examples shows a simple but not-so-trivial API.
The API represents a fictional library with a catalogue of books, related with authors and publishers.
All Resources includes examples of links.
Book GET also also shows how to return different level of details, either embedding or linking related resources.
Beyond GET examples for all resources, it also includes other "command" endpoints, like for adding a book to the collection, borrowing and returning books.
There's a pretty basic example in this repository. A more advanced showcase can be found in Spring RESTBucks.
Here's sample EchoService described step-by-step with explanations in code. It is using Spring Boot HATEOAS and shows sample Spock test with TestRestTemplate.
HATEOAS means (at least in my mind :-) ) that you treat a HTTP resource as a state machine, which means that it can change depending on its (system) internal state.
The most common example is a bank account as a resource. Accessing the resource (account) returns various informations about it and links to operations that can be performed on it. And those operations (hence available links) depend on the account's state. If a user has money then the links could be { "deposit": "deposit-url", "withdraw": "withdraw-url" }. When a user has no money on the account, then the returned links (available actions) could be { "deposit": "deposit-url" }. So the list of available operations/actions/links varies and depends on resource's state.
Another common example is having different menu items depending on user's role/permissions. In apps, which generate whole page on server side, you could generate links to different actions in page template by simple checks: if (isAdmin(currentUser)) { {generate secret link} } else { ... }. But when using REST services most clients are JavaScript apps, where you can't do any permissions checks. So here HATEOAS helps by returning menu actions (links) depending on user's role/permission on server side and REST client doesn't have to worry about it.
Related
I’m redesigning the REST API for a small SaaS I built. Currently there’s a route /entries that doesn’t require any authentication. However, if the client authenticates with sufficient privileges, the server will send additional information (ex: the account associated with each entry).
The main problem I see with this is that a client attempting to request protected data with insufficient privileges will still receive a 200 response, but without the expected data, instead of a 401 Unauthorized.
The alternatives I came up with are:
Split the endpoint into two endpoints, ex /entries and /admin/entries. The problem with this approach is that there are now two different endpoints for essentially the same resource. However, it has the advantage of being easy to document with OpenAPI. (Additionally, it allows for the addition of a /entries/:id/account endpoint.)
Accept a query parameter ?admin=true. This option is harder to document. On the other hand, it avoids having multiple URIs for a single entry.
Is there a standard way to structure something like this?
Related question: Different RESTful representations of the same resource
The alternatives I came up with are
Note that, as far as HTTP/REST are concerned, your two alternatives are the same: in both cases you are introducing a new resource.
The fact that in one case you use path segments to distinguish the two identifiers and in the other case you are using the query part doesn't change the fact that you have two resources.
Having two resources with the same information is fine - imagine two web pages built from the same information.
It's a trade off - the HTTP application isn't going to know that these resources have common information, and so won't know that invalidating one cached resource should also invalidate the other. So just like with web pages, you can get into situations where the representations that you have in your cache aren't consistent with each other.
Sometimes, the right answer is to use links between different resources - have "the" information in one place, and everywhere else has links that allow you to find that one place. Again, trade-offs.
HTTP isn't an infinitely flexible application protocol. It's really good at transferring documents over a network, especially at "web scale".
There have been attempts at using Link headers to trigger invalidation of other cached resources, but as far as I have been able to tell, none of them has made it past the proposal stage.
While reading some articles about writing web servers using Twisted, I came across this page that includes the following statement:
While it's convenient for this example, it's often not a good idea to
make a resource that POSTs to itself; this isn't about Twisted Web,
but the nature of HTTP in general; if you do this, make sure you
understand the possible negative consequences.
In the example discussed in the article, the resource is a web resource retrieved using a GET request.
My question is, what are the possible negative consequences that can arrive from having a resource POST to itself? I am only concerned about the aspects related to the HTTP protocol, so please ignore the fact that I mentioned about Twisted.
The POST verb is used for making a new resource in a collection.
This means that POSTing to a resource has no direct meaning (POST endpoints should always be collections, not resources).
If you want to update your resource, you should PUT to it.
Sometimes, you do not know if you want to update or create the resource (maybe you've created it locally and want to create-or-update it). I think that in that case, the PUT verb is more appropriate because POST really means "I want to create something new".
There's nothing inherently wrong about a page POSTing back to itself - in fact, many of the widely-used frameworks (ASP.NET, etc.) use that method to handle various events that happen on the client - some data is posted back to the same page where the server processes it and sends a new reponse.
I'm considering an SOA architecture for a set of servives to support a business that Im consulting for, previously we used database integration where each application picked out what it need from a shared MS SQL database and worked with it etc.. We had various apps integrating with the monster database including java, .net and microsoft access, there was referential integrity as everything was tightly coupled.
I'm a bit confused about how to support data sharing between services.
Lets take Product Service which sits on top of a the Product database provided by the wholesaler each month. We build a domain model and sit this on to of the database with Hibernate or whatvever, implentation wise Product is a large object graph given the information provided by the wholesaler about the product.
Now lets say the Review service, Pricing Service, Shipping Service, and Stock Service will subscribe to ProductUpdated, ProductAdded, ProductDeleted. The problem is that each service only need part or some parts of the information about the Product. Shipping might only need the dimensions and weight. Pricing might only need product id, wholesale cost, volume discount, price effective to date. Review might need product id, product name, producer.
Is it standard practice just to publish the whole Product (suitable non-subscriber-specific contracts e.g. ProductUpdated, and a suitable schema - representing all product object graph) and let the subscribers map whatever they need to their domain models (or heck do what they want with, might not even have a domain model)...
Or as I write this I'm thinking maybe:
Product Service Publishes ProductAdded message (does not included product details just an ID of product and maybe a timestamp)
Pricing Service subscribes to ProductAdded and publishes RequestPricingForProduct message
Product Service Publishes ResultForPricingForProduct message
Hmm.. seems a little better... but it feels like I'm building the contract for Product Service based on what other services I can identify and what they are going to need, perhaps in future XYZ Service requires something different. Im going to stop there as I think it's getting clearer where I'm confused... perhaps the above will work because I should expose a way to return whatever that should be public hmmm right.
Any comments or direction greatly appreciated. Sorry if this appears half baked.
I actually think the solution to this problem is to NOT share the data. SOA means that data is owned by a service - it is the technical authority of that data. I suggest reading a few Pat Helland articles, such as Data On The Inside, Data On The Outside.
The only thing that should be shared between these different services is the primary key - the ProductId in your example. Otherwise, for each service, the data that needs to be transactionally consistent goes together.
There does not need to be one "Product". Each service can have a different view of the product in their service. For the Pricing service, you have a productId and a price. For the review service, a productId and a review. And so on.
Where this starts to confuse people is how to display this data in the UI if it's from all these disparate services. How can you show a list of reviews for a product that has the product name from the ProductService and the review text from the ReviewService?
The answer to that is to compose the UI from all the different services. Get the product from the product service and get the review data from the review service and then combine that data in the UI.
I was in your position recently. The problem with directly exposing the underlying object through the service is that you increase coupling between layers, and there becomes little point in using a Service Oriented Achitecture at all. You would not be able to change these objects or business rules without affecting the web service too.
It sounds like you are on the right track. If you are serious about seperating your layers, then the most common pattern is to create a new separate set of message classes just for the web service, potentially each service, and translate your internal objects back and forth.
For an example of how to set up your service layer in this manner see the "Service Interface" pattern. On the client side of the service, there is an opposite pattern called "Service Gateway".
The Application Architecture Guide 2.0 has a whole chapter dedicated to the types of the decisions you are making (http://apparchguide.codeplex.com/Wiki/View.aspx?title=Chapter%2013%20-%20Service%20Layer%20Guidelines). I would download the whole guide.
Here is the portion most relevant to you. Long story short, if you take the time to create new coarse-grained methods, and message-based objects, you'll end up with a much better web service:
Consider the following guidelines when designing a service interface:
Consider using a coarse-grained interface to batch requests and minimize the number of calls over the network.
Design service interfaces in such a way that changes to the business logic do not affect the interface.
Do not implement business rules in a service interface.
Consider using standard formats for parameters to provide maximum compatibility with different types of clients.
Do not make assumptions in your interface design about the way that clients will use the service.
Do not use object inheritance to implement versioning for the service interface.
I understand (I think) the basic idea behind RESTful-ness. Use HTTP methods semantically - GET gets, PUT puts, DELETE deletes, etc... Right? thought I understood the idea behind REST, but I think I'm confusing that with the details of an HTTP implementation. What is the driving idea behind rest, why is this becoming an important thing? Have people actually been using it for a long time, in a corner of the internets that my flashlight never shined upon?
The Google talk mentions Atom Publishing Protocols having a lot of synergy with RESTful implementations. Any thoughts on that?
This is what REST might look like:
POST /user
fname=John&lname=Doe&age=25
The server responds:
201 Created
Location: /user/123
In the future, you can then retrieve the user information:
GET /user/123
The server responds (assuming an XML response):
200 OK
<user><fname>John</fname><lname>Doe</lname><age>25</age></user>
To update:
PUT /user/123
fname=Johnny
Here's my view...
The attraction to making RESTful services is that rather than creating web-services with dozens of functional methods, we standardize on four methods (Create,Retrieve, Update, Destroy):
POST
GET
PUT
DELETE
REST is becoming popular because it also represents a standardization of messaging formats at the application layer. While HTTP uses the four basic verbs of REST, the common HTTP message format of HTML isn't a contract for building applications.
The best explanation I've heard is a comparison of TCP/IP to RSS.
Ethernet represents a standardization on the physical network. The Internet Protocol (IP) represents a standardization higher up the stack, and has several different flavors (TCP, UDP, etc). The introduction of the "Transmission Control Protocol" (guaranteed packet delivery) defined communication contracts that opened us up to a whole new set of services (FTP, Gopher, Telnet, HTTP) for the application layer.
In the analogy, we've adopted XML as the "Protocol", we are now beginning to standardize message formats. RSS is quickly becoming the basis for many RESTful services. Google's GData API is a RSS/ATOM variant.
The "desktop gadget" is a great realization of this hype: a simple client can consume basic web-content or complex-mashups using a common API and messaging standard.
HTTP currently is under-used and mis-used.
We usually use only two methods of HTTP: GET and POST, but there are some more: DELETE, PUT, etc (http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html)
So if we have resources, defined by RESTful URLs (each domain object in your application has unique URL in form of http://yoursite.com/path/to/the/resource) and decent HTTP implementation, we can manipulate objects in your domain by writing sentences:
GET http://yoursite.com/path/to/the/resource
DELETE http://yoursite.com/path/to/the/resource
POST http://yoursite.com/path/to/the/resource
etc
the architecture is nice and everything.
but this is just theoretical view, real world scenarios are described in all the links posted in answers before mine.
Lets go to history, Talk about the Roy Fielding Research – “Architectural Styles and the Design of Network-based Software Architectures“. Its a big paper and talks a lot of various stuff. But as a standard engineer How you would like to explain the clear meaning of REST (Representational State Transfer), and what is its Architectural Style.
Here is my way to explain – “What is REST”.
See this www(world wide web) running on top of various hardwares e.g. routers,servers,firewalls, cloud infrastructures,switches,LAN,WAN. The overall objective of this www(world wide web) to distribute hypermedia. This world wide web equipped with various services e.g. informational based services, websites, youtube channels, dynamic websites, static websites. This world wide web uses HTTP protocol to distribute hypermedia across the world with a client/server mechanism. This HTTP Protocol works on top of TCP/IP or other appropriate network stack.
This HTTP protocol is using eight methods to manage the ‘protocol of distribution’ or ‘Architectural Style of Distribution’. Those eight methods are namely : OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT.
But on Top of this HTTP, web applications are using its own way of distributing hypermedia e.g web applications are using web services which are highly tied with clients and servers ‘or’ web applications are using its own way of designed client/server mechanism to make such distribution channel on top of HTTP.
What Roy Fielding Research says , that these eight methods OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT of HTTP are so successful to deliver HyperMedia to all across the world on top of variety of hardware resources and network stacks with client/server mechanism, Why don’t we use the similar strategy with our web based application as well. On this GET,POST,DELETE and PUT are used the most. so four methods deliver HyperMedia to all across the world.
In REST API Architecture Style application, a web application need to design the business logic(resides in a server e.g. Tomcat,Apache HTTP) with all set of object entities(e.g. Customer is an entity) and possible operations(e.g.‘Retrieve Customer Information based on a customer id’) on them. Those possible operations with these entities should be designed with four main operations or methods namely- Create,Retrieve,Update,Delete. These entities called as resources and these are presented or represented in a form e.g. JSON or XML or something else. We have Client(Browsers) who calls Create,Retrieve,Update,Delete (CRUD) methods to perform the appropriate function on such resource resides in the Server.
But as explained the concept of Representation, means the way entities of business logic or objects are represented. but what about with ‘State Transfer’ ?.
The State Transfer, its talks about the “state of communication” from Client to Server. It talks about the design of ‘state transfers’ from Client to Server e.g. Client first called the operation ‘Create Customer’, after calling this what would be next state of customer or states of customer which ‘client’ can call. Its state may be to ‘retrieve the created client data’, ‘update the client data’ or what
REST is an architecture where resources are defined and addressed.
To understand REST best, you should look at the Resource Oriented Architecture (ROA) which gives a set of guidelines for when actually implementing the REST architecture.
REST does not need to be over HTTP, but it is the most common. REST was first created by one of the creators of HTTP though.
Ok, so I'm looking for a bit of architecture guidance, my team is getting a chance to re-cast certain decisions with a new feature that we're building, and I wanted to see what SO thought :-) There are of course certain things that we're not changing, so the solution would have to fit in this model. Namely, that we've got an ASP.NET application, which uses web services to allow users to perform actions on the system.
The problem comes in because, as with many systems, different users need access to different functions. Some roles have access to Y button, and others have access to Y and B button, while another still only has access to B. Most of the time that I see this, developers just put in a mish-mosh of if statements to deal with the UI state. My fear is that left unchecked, this will become an unmaintainable mess, because in addition to putting authorization logic in the GUI, it needs to be put in the web services (which are called via ajax) to ensure that only authorized users call certain methods.
so my question to you is, how can a system be designed to decrease the random ad-hoc if statements here and there that check for specific roles, which could be re-used in both GUI/webform code, and web service code.
Just for clarity, this is an ASP.NET web application, using webforms, and Script# for the AJAX functionality. Don't let the script# throw you off of answering, it's not fundamentally different than asp.net ajax :-)
Moving from the traditional group, role, or operation-level permission, there is a push to "claims-based" authorization, like what was delivered with WCF.
Zermatt is the codename for the Microsoft class-library that will help developers build claims-based applications on the server and client. Active Directory will become one of the STS an application would be able to authorize against concurrently with your own as well as other industry-standard servers...
In Code Complete (p. 411) Steve McConnell gives the following advice (which Bill Gates reads as a bedtime story in the Microsoft commercial).
"used in appropriate circumstances, table driven code is simpler than complicated logic, easier to modify, and more efficient."
"You can use a table to describe logic that's too dynamic to represent in code."
"The table-driven approach is more economical than the previous approach [rote object oriented design]"
Using a table based approach you can easily add new "users"(as in the modeling idea of a user/agent along with it's actions). Its a good way to avoid many "if"s. And I've used it before for situations like yours, and it's kept the code nice and tidy.