EzDevInfo.com

Hateoas

A PHP library to support implementing representations for HATEOAS REST web services. Hateoas - A PHP library to support implementing representations for HATEOAS REST web services.

Is That REST API Really RPC? Roy Fielding Seems to Think So

A large amount of what I thought I knew about REST is apparently wrong - and I'm not alone. This question has a long lead-in, but it seems to be necessary because the information is a bit scattered. The actual question comes at the end if you're already familiar with this topic.

From the first paragraph of Roy Fielding's REST APIs must be hypertext-driven, it's pretty clear he believes his work is being widely misinterpreted:

I am getting frustrated by the number of people calling any HTTP-based interface a REST API. Today’s example is the SocialSite REST API. That is RPC. It screams RPC. There is so much coupling on display that it should be given an X rating.

Fielding goes on to list several attributes of a REST API. Some of them seem to go against both common practice and common advice on SO and other forums. For example:

  • A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API). ...

  • A REST API must not define fixed resource names or hierarchies (an obvious coupling of client and server). ...

  • A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. ...

The idea of "hypertext" plays a central role - much more so than URI structure or what HTTP verbs mean. "Hypertext" is defined in one of the comments:

When I [Fielding] say hypertext, I mean the simultaneous presentation of information and controls such that the information becomes the affordance through which the user (or automaton) obtains choices and selects actions. Hypermedia is just an expansion on what text means to include temporal anchors within a media stream; most researchers have dropped the distinction.

Hypertext does not need to be HTML on a browser. Machines can follow links when they understand the data format and relationship types.

I'm guessing at this point, but the first two points above seem to suggest that API documentation for a Foo resource that looks like the following leads to tight coupling between client and server and has no place in a RESTful system.

GET   /foos/{id}  # read a Foo
POST  /foos/{id}  # create a Foo
PUT   /foos/{id}  # update a Foo

Instead, an agent should be forced to discover the URIs for all Foos by, for example, issuing a GET request against /foos. (Those URIs may turn out to follow the pattern above, but that's beside the point.) The response uses a media type that is capable of conveying how to access each item and what can be done with it, giving rise to the third point above. For this reason, API documentation should focus on explaining how to interpret the hypertext contained in the response.

Furthermore, every time a URI to a Foo resource is requested, the response contains all of the information needed for an agent to discover how to proceed by, for example, accessing associated and parent resources through their URIs, or by taking action after the creation/deletion of a resource.

The key to the entire system is that the response consists of hypertext contained in a media type that itself conveys to the agent options for proceeding. It's not unlike the way a browser works for humans.

But this is just my best guess at this particular moment.

Fielding posted a follow-up in which he responded to criticism that his discussion was too abstract, lacking in examples, and jargon-rich:

Others will try to decipher what I have written in ways that are more direct or applicable to some practical concern of today. I probably won’t, because I am too busy grappling with the next topic, preparing for a conference, writing another standard, traveling to some distant place, or just doing the little things that let me feel I have I earned my paycheck.

So, two simple questions for the REST experts out there with a practical mindset: how do you interpret what Fielding is saying and how do you put it into practice when documenting/implementing REST APIs?

Edit: this question is an example of how hard it can be to learn something if you don't have a name for what you're talking about. The name in this case is "Hypermedia as the Engine of Application State" (HATEOAS).


Source: (StackOverflow)

HATEOAS: absolute or relative URLs?

In designing a RESTful Web Service using HATEOAS, what are the pros and cons of showing a link as a complete URL ("http://server:port/application/customers/1234") vs. just the path ("/application/customers/1234")?


Source: (StackOverflow)

Advertisements

Actual examples for HATEOAS (REST-architecture) [closed]

as everyone may have noticed, there are lot of fake/rudimentary REST-APIs in the wild (which implement a HTTP-API and call it REST without following the hypertext-as-the-engine-of-application-state requirement, which led to the famous rant of Roy T. Fielding, the man who first specified the REST-paradigm).

I've been unable to find any practical examples of a truly hypertext driven REST-implementation along with the associated application-specific media-type definitions for the state transitions.

Are there any publicly accessible examples of such implementations?


Source: (StackOverflow)

RESTful API runtime discoverability / HATEOAS client design

For a SaaS startup I'm involved in, I am building both a RESTful web API and a couple of client apps on different platforms that consume it. I think I've got the API figured out, but now I'm turning to the clients. As I've been reading about REST, I see that a key part of REST is discovery, but there seems to be a lot of debate between two different interpretations of what discovery really means:

  1. Developer discovery: The developer hard-codes copious amounts of API details into the client, such as resource URI's, query parameters, supported HTTP methods, and other details that they've discovered through browsing the docs and experimenting with the API's responses. This type of discovery IMHO necessitates cool linkage and the API versioning question, and leads to hard coupling of the client code to the API. Not much better than if using a well-documented collection of RPC's it seems.

  2. Runtime discovery - The client app itself is able to figure out everything it needs with little or no out-of-band information (presumably, only a knowledge of the media types the API deals with.) Links can be hot. But to make the API very efficient, a lot of link templating for query parameters seems to be needed, which makes out-of-band info creep back in. There are possibly other difficulties I haven't thought of yet since I haven't gotten to that point in development. But I do like the idea of loose coupling.

Runtime discovery seems to be the holy grail of REST, but I'm seeing precious little discussion about how to implement such a client. Almost all REST sources I've found seem to assume Developer discovery. Anyone know of some Runtime discovery resources? Best practices? Examples or libraries with real code? I'm working in PHP (Zend Framework) for one client. Objective-C (iOS) for the other.

Is Runtime discovery a realistic goal, given the present set of tools and knowledge in the developer community? I can write my client to treat all of the URI's in an opaque manner, but how to do this most efficiently is a question, especially over low-bandwidth connections. Anyway, URI's are only part of the equation. What about link templating in the Runtime context? How about communicating what methods are supported, aside from making a lot of OPTIONS requests?


Source: (StackOverflow)

How to create a good hypermedia format using JMSSerializerBundle?

Lets say I want to create an XML-response that will looks something like the following:

<?xml version="1.0" encoding="utf‐8"?>
<product xmlns="urn:com.acme.prods" xmlns:atom="http://www.w3.org/2005/xlink">
  <id>1234</id>
  <name>Red Stapler</name>
  <price currency="EUR">3.14</price>
  <atom:link rel="payment" type="application/com.acme.shop+xml"
             rel='nofollow' href="http://acme.com/products/1234/payment" />
</product>

Given an domain model that looks something like the following:

<?php
// Product.php
namespace Acme\Bundle\ProductBundle\Entity;
use Acme\Bundle\ProductBundle\Money\Money;

class Product
{
  /**
   * @var integer
   */
  private $id;

  /**
   * @var string
   */
  private $name;

  /**
   * @var Money
   */
  private $price;

  [..]
}

And a money-class along the lines of:

<?php
// Money.php
namespace Acme\Bundle\ProductBundle\Money;

class Money
{
  /**
   * @var string
   */
  private $currency;
  /**
   *
   */
  private $amount;
}

Now, to my questions. It would be pretty simple to create a response that looks like the following

<?xml version="1.0" encoding="utf‐8"?>
<product>
  <id>1234</id>
  <name>Red Stapler</name>
  <price currency="EUR">3.14</price>
</product>

using either annotations, XML or YAML to tell JMSSerializerBundle how to serialize the Product-object. However, the xmlns:atom and <atom:link> entries should not be specified by the entity, since it should have no concept of how and where it is located. You could also imagine more links with different rel-attributes, such as edit.
One solution that comes to mind would be a service that listens to serialization events for specific objects, and adds these attributes and tags as appropriate. The service could use DI to get hold of the Request, Router-service etc to generate these links in a format that is suitable for the requested format. I.E in an XML-response, it could set the appropriate type to application/media-format+xml, whereas in a json-response, it could generate something like

"links": [
   {
     "rel": "payment", 
     "type": "application/media-format+json", 
     "href": "[...]"
   }
]

Now, in the documentation for JMSSerializerBundle, I find annotations for @PreSerialize, and @PostSerialize, but they seem to only be able to call methods on the object being serialized.
Does anyone know how/if this can be achieved? Or do I have to use a templating engine such as Twig and manually create the XML-response?


Source: (StackOverflow)

Link Relations in JSON Representations

I'm designing a RESTful API based on JSON representations. In order to comply with HATEOAS, I use links between resources extensively. Therefore, I followed this suggestion for serializing links in way very similar to ATOM links.

Now I have sometimes problems identifying the correct link relation type. When a resource contains a link to itself, the self relation is obvious. It gets more complex when the resources are collections and aggregations of sub-resources, or contain many links to related resources.

Take a blog post as an example, and think of a resource that returns a snapshot of the blog post – including the author, tags and comments of this blog post. Obviously, this resource containg many subresources and should of course also provides separate links to them:

Sample Resource:

{
   "blogpost":{
      "link":{
         "rel":"self",
         "href":"http://blog/post/4711"
      },
      "author":{
         "name":"Bob",
         "link":{
            "rel":"???",
            "href":"http://author/uri"
         }
      },
      "title":"foobar",
      "content":"A long article here…",
      "comments":[
         {
            "comment":"great article",
            "link":{
               "rel":"???",
               "href":"http://blog/post/4711/comment/1"
            },
            "author":{
               "name":"John Doe",
               "link":{
                  "rel":"???",
                  "href":"http://author/uri"
               }
            }
         }
      ],
      "tags":[
         {
            "value":"foo",
            "link":{
               "rel":"???",
               "href":"http://blog/post/4711/tag/foo"
            }
         }
      ]
   }
}

So what are appropriate relations for the given links? I know that there are relation types such as tag, but not all of my resources match the existing relation types. Or is it okay to use self when referring to the author/tag/comment, because it relates to the context of the enclosing JSON (sub-)object? What is the semantical entity self is referring to?

RFC 5988 states:

The context of the link is either a feed IRI or an entry ID, depending on where it appears

How can I interpret this in terms of JSON? Is each new object {…} a new context?

Thanks!


Source: (StackOverflow)

How can I use HATEOAS and Query Parameters for RESTful search?

I would like to design a RESTful search URI using query parameters. For example, this URI returns a list of all users:

GET /users

And the first 25 users with the last name "Harvey":

GET /users?surname=Harvey&maxResults=25

How can I use hypermedia to describe what query parameters are allowed by the "/users" resource? I noticed that the new Google Tasks API just documents all the query parameters in the reference guide. I will document the list, but I would like to do it with HATEOAS too.

Thank you in advance!


Source: (StackOverflow)

HATEOAS: concise description

I am trying to get a clear and concise understanding of HATEOAS, and I am by no means an expert WRT REST (I think I get it though, thanks to this http://tomayko.com/writings/rest-to-my-wife)

Can anyone suggest an equally enlighenting blog/article WRT HATEOAS?


Source: (StackOverflow)

How should i handle HATEOAS links and References in JSON?

I'm in the process of designing a REST api and to be as RESTful as it gets I want to incorporate HATEOAS into the json responses.

Adding URLs to related resources is easy enough, but there was some discussion over the structure to use for those links.

A LOT of articles I found use a structure borrowed from ATOM feeds:

"links": [ 
    {"rel": "self", "href":"http://example.org/entity/1"},
    {"rel": "friends", "href":"http://example.org/entity/1/friends"}, ... 
]

This raised some questions:

  • Why use an array as a container? According to a javascript developer I know, access to the links would be easier with the links as properties of an object. For example:

    "self":    { "href":"http://example.org/entity/1" }, /* (facebook uses this) */  
    "friends": { "href":"http://example.org/entity/1/friends", "type": "..."}
    
  • Is there a common json structure (beside adapting atom again) to describe references in resource properties? (for example the sender of a message).

    The reference should probably be resolved as a url again, but would it be bad to include the simple id as well? kind of like:

    "sender": { 
        "id": 12345,
        "href": "resource-uri"
    }
    

    My way of thought is that while HATEOAS makes it so a client doesn't need a lot of knowledge to use an api, I'm kind of reluctant to remove the possibility to USE that knowledge (like accessing the profile picture by building the link client-side without looking up the user first)


Source: (StackOverflow)

How useful/important is REST HATEOAS ( maturity level 3)?

I'm getting involved in a project where some senior team members believe that a REST API has to be HATEOAS compliant and implement all Richardson's maturity levels (http://martinfowler.com/articles/richardsonMaturityModel.html)!

AFAIK most REST implementations are not HATEOAS compliant and there should be a good reason why more people aren't doing it. I can think of reasons like added complexity, lack of frameworks (server and client sides), performance concern and...

What do you think? Have you had any experience with HATEOAS in a real world project?


Source: (StackOverflow)

Does anyone know of an example of a RESTful client that follows the HATEOAS principle?

So by now I'm getting the point that we should all be implementing our RESTful services providing representations that enable clients to follow the HATEOAS principle. And whilst it all makes good sense in theory, I have been scouring the web to find a single good example of some client code that follows the idea strictly.

The more I read, the more I'm starting to feel like this is an academic discussion because no-one is actually doing it! People can moan all they like about the WS-* stack's many flaws but at least it is clear how to write clients: you can parse WSDL and generate code.

Now I understand that this should not be necessary with a good RESTful service: you should only need to know about the relationships and representations involved and you should be able to react dynamically to those. But even still, shouldn't this principle have been distilled and abstracted into some common libraries by now? Feed in information about the representations and relationships you might receive and get some more useful higher level code you can use in your application?

These are just half-baked ideas of mine really, but I'm just wary that if I dive in and write a properly RESTful API right now, no-one is actually going to be able to use it! Or at least using it is going to be such a pain in the behind because of the extra mile people will have to go writing glue code to interpret the relationships and representations I provide.

Can anyone shed any light on this from the client perspective? Can someone show an example of properly dynamic/reactive RESTful client code so that I can have an idea of the audience I'm actually writing for? (better still an example of a client API that provides some abstractions) Otherwise its all pretty theoretical....

[edit: note, I've found a similar question here, which I don't think was really answered, the author was palmed off with a Wikipedia stub!]


Source: (StackOverflow)

Implement HATEOAS with HAL in Jersey

One of the key points of building a RESTful API is HATEOAS. Now, Jersey offers a linking ability which is quite good (see this link). But I have seen the draft of the HAL Specification and it seems to be a well thought piece of work.

I am interested if there is some lib that makes it easy to adhere to HAL in Jersey. I have seen the references mentioned in the draft like https://github.com/HalBuilder. But I am using direct POJO marshalling and I do not know how to mix that with Halbuilder.

So, is there already some lib that incorporates HAL into Jersey? Or maybe I can use some kind of filter to enhance the generated POJOs manually? If yes, can someone give me a clue where to look next to accomplish this?


Source: (StackOverflow)

HATEOAS client with AngularJS

I was wondering if there were any features hidden in Angular or exposed by some 3rd-party libraries to easily create HATEOAS-compliant Restful clients.

On backend side, I am using Spring Data/REST to produce an HATEOAS JSON API. Consuming it, though, is quite another story.

For instance, I've got those 3 entities:

  • Company {name, address}
  • Employee {firstName, lastName, employer[Company]}
  • Activity {rate, day, employee[Employee], client[Company]}

and requesting an activity (the most complex entity of the model) produces something like this:

{
    links: [],
    content: [{
            rate: 456,
            day: 1366754400000,
            links: [{
                rel: "self",
                href: "http://localhost:8080/api/activities/1"
            },
            {
                rel: "activities.activity.client",
                href: "http://localhost:8080/api/activities/1/client"
            },
            {
                rel: "activities.activity.employee",
                href: "http://localhost:8080/api/activities/1/employee"
            }]
        }]
}

My API talks in terms of REST (resources identified by links). An Activity has an Employee for instance. What I really want to use is : {rate: 456, day: 1366754400000, employee: {firstName:"xxx", lastName:"xxx" ...}}.

However, as you can see in the first output, my Activity only contains a link to the employee, not its data. Is there anything in Angular or in a 3rd-party library to resolve those links and embed the resulting data instead?

Any input on this?

Thanks in advance!


Source: (StackOverflow)

REST Client Implementation Embracing HATEOAS Constraint?

Does anybody know of an implementation of a REST client that embraces the constraint of Hypermedia as the Engine of Application State (HATEOAS)?

The Sun Cloud API seems to be a good candidate, judging from the way it's documented and a statement by the author to the effect that Ruby, Java, and Python implementations were in the works. But so far I've found no trace of the code.

I'm looking for anything - even a partial implementation would be helpful.


Source: (StackOverflow)

How to create a custom media type (application/vnd) for a RESTful web service?

I'm playing with REST right now and thought I properly implement HATEOAS just to get all concepts right.

For that I want to create my own media types (application/vnd[...]+xml and application/vnd[...]+json).

One first question: Does the media type define the contract between my server and client?

The media type will define my message formats so I need to add XML schema and JSON schema to go with the new media types (so that REST clients know what's coming in messages and what to send back).

I've done some research on the web but the details of how one does this are missing. Does it only involve writing exhaustive specification/documentations or are there some technical steps to implement? (I don't have to register it with IANA do I?)

How can a new - fully functional - application/vnd media type be created? and what do you need to take care of so that clients can properly use it?


Source: (StackOverflow)