<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>The Amiable API</title>
	<atom:link href="http://theamiableapi.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://theamiableapi.com</link>
	<description>On developer-friendly API design</description>
	<lastBuildDate>Tue, 14 May 2013 19:48:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='theamiableapi.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>The Amiable API</title>
		<link>http://theamiableapi.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://theamiableapi.com/osd.xml" title="The Amiable API" />
	<atom:link rel='hub' href='http://theamiableapi.com/?pushpress=hub'/>
		<item>
		<title>Demystifying REST Constraints</title>
		<link>http://theamiableapi.com/2012/05/06/demystifying-rest-constraints/</link>
		<comments>http://theamiableapi.com/2012/05/06/demystifying-rest-constraints/#comments</comments>
		<pubDate>Mon, 07 May 2012 01:45:50 +0000</pubDate>
		<dc:creator>Ferenc Mihaly</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Interface]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Usability]]></category>

		<guid isPermaLink="false">http://theamiableapi.com/?p=990</guid>
		<description><![CDATA[Who do you think the actor is in the sentence &#8220;Brenda was happy to interview the actor&#8221;, a Hollywood celebrity or a member of the local community theater? The REST constraints described in Roy Fielding’s dissertation enjoy celebrity status. I cannot mention constraints without people immediately assuming that I either talk about them, ignore them, [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=990&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p style="text-align:justify;">Who do you think the actor is in the sentence &#8220;Brenda was happy to interview the actor&#8221;, a Hollywood celebrity or a member of the local community theater? The REST constraints described in <a title="Roy Fielding: Architectural Styles and the Design of Network-based Software Architectures" href="http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm">Roy Fielding’s dissertation</a> enjoy celebrity status. I cannot mention constraints without people immediately assuming that I either talk about them, ignore them, or argue against them. Few realize that I talk about <em>additional</em> application constraints or perhaps about <em>strengthening</em> one of Fielding’s constraints.  I wish I could use another word, but the well-known REST constraints and application-specific constraints aren’t much different and combine to define a concrete RESTful protocol.</p>
<p style="text-align:justify;">I want to be free to talk about constraints because by definition a protocol is a set of rules, many of them constraints. The Wikipedia definition of a communication protocol, “…a system of digital message formats and rules for exchanging those messages in or between computing systems and in telecommunications” mentions rules, but examples from the <a title="Dictionary definition of the word protocol" href="http://www.merriam-webster.com/dictionary/protocol"> Merriam-Webster dictionary</a> illustrate even better that the word protocol is synonymous with a set of rules:</p>
<ul>
<li>The soldier&#8217;s actions constitute a breach of military <em>protocol</em> [rules or regulations].</li>
<li>They did not follow the proper diplomatic <em>protocols</em> [rules or etiquette].</li>
<li>What is the proper <em>protocol</em> [rules or conventions] for declining a job offer?</li>
</ul>
<p style="text-align:justify;">The <a title="1925 Geneva Protocol" href="http://www.un.org/disarmament/WMD/Bio/1925GenevaProtocol.shtml">Geneva Protocol</a> and the <a title="Kyoto Protocol" href="http://unfccc.int/kyoto_protocol/items/2830.php">Kyoto Protocol</a> set forth international regulation agreed upon by the participating countries. Similarly, the rules of a communication protocol are agreed upon by participants in the communication, not imposed by an external authority. Standards and specifications like RFC 2616 merely formalize the results of the agreement.</p>
<p style="text-align:justify;">A constraint is a rule. What kind of rule is surprisingly hard to define exactly. Some would say a constraint is a rule about what <em>not</em> to do. This is close, but not close enough. Not close enough because any statement about what to do can be rephrased, however awkwardly, to say not to do the opposite. You can say &#8220;the protocol must be stateless&#8221; or &#8220;the protocol must not force the server to keep track of the client&#8217;s state&#8221;. Either way, it is the same constraint.</p>
<p style="text-align:justify;">Constraints are like good parenting: instead of telling your kinds what to do, you set safe, age-appropriate limits, but otherwise let your kinds live their life and make their own decisions. Protocol constraints are used the same way to ensure safe, reliable, performant communication without restricting what the communication should be about. Constraints are also used to remove unessential variations which would complicate protocol implementation without any clear benefits. For example you can make you protocol simpler if you support JSON only. This is a valid constraint as long as XML support is not essential.</p>
<p style="text-align:justify;">Constraints should never restrict an essential freedom. This is so important that we have an expression for such mistake:<em> to over-constrain</em>. I find it quite unfortunate that the noun <em>constraint</em> derives from the verb <em>to constrain</em>, which has meanings like “restrict by force” or “to secure by or as if by bonds”. These meanings suggest firmness and strength. Some of us subconsciously think of constraints as exceptionally strong and important rules. If somebody ever reminded you in a stern voice of a REST constraint, you know what I mean. To discuss constraints rationally we have to let go of our emotions. We don&#8217;t have to enforce constraints more vigorously than other protocol rules.</p>
<p style="text-align:justify;">Let me give you some examples of relatively strict constraints. To show you that my use of constraints is consistent with Fielding&#8217;s and that some of his REST constraints are implicit in mine, I&#8217;ll gradually relax mine until they become equivalent with two of his.</p>
<p style="text-align:justify;">Imagine a simple HTTP interface for a key-value data store. Clients send GET, PUT, and DELETE requests using URIs as keys and message bodies as values. The following constraint expresses a one-to-one mapping between URIs and message bodies: “As a response to a GET request the server must either return the status code 404 Not Found, or 200 OK and a message body which is a copy of the message body received in the last successful PUT request to the same URI”. Just to show I can, I expressed this as a rule about what the server must do. The remaining constraints are indeed easier to express in terms of what the server must <em>not</em> do, such as:</p>
<ol>
<li>The server must not return the 404 status code if there was a previous successful PUT request to the same URI</li>
<li>The server must not return other HTTP status codes, for example 302</li>
<li>The server must not allow the byte sequence representing the value assigned to the URI to change by any other means except as a response to an explicit PUT request</li>
<li>The server must not return a message body for any URI for which no value was yet set</li>
</ol>
<p>… and a few more. These constraints give my protocol some nice, useful properties. I can fully test my server via the protocol, for example.</p>
<p style="text-align:justify;">&#8220;This is not REST&#8221;, you may object, &#8220;where is the hypermedia?&#8221; Good point. The hypermedia constraint does not say you must use hypermedia everywhere.  That would be a bit too strict and would render most of the media types from the IANA registry unfit for REST. The constraint says to use hypermedia to indicate what the valid client state transitions are and to help clients discover URIs. In my protocol all client state transitions are valid and the client does not need to discover URIs because it controls the URI space. Hence there is no hypermedia. You may say that the hypermedia constraint is not applicable. I prefer to say that it is satisfied.</p>
<p style="text-align:justify;">To extend the applicability of my protocol beyond key-value data stores I need to relax some of my constraints. To turn my data store into a simple web server I need to eliminate constraint 4 and allow URIs pre-loaded with static content. Unfortunately the loss of constraint 4 also means that my clients no longer know what URIs exist and what they mean. Now I do indeed need to satisfy the hypermedia constraint. There are still many different ways to do it, for example I can provide a site map. Clients can still rely on their knowledge that values associated with URIs never change, use caches that never expire, for example.</p>
<p style="text-align:justify;">Now imagine that my URIs identify Wikipedia articles. I don’t expect articles to change much over time, but I want to allow minor edits or formatting changes by eliminating constraint 3. Without constraint 3, however, message bodies for two successive GET requests may no longer be identical and I lose my ability to programmatically verify URIs still point to valid pages. Indeed, Wikipedia needs volunteers to make sure pages were not vandalized.</p>
<p style="text-align:justify;">I hope I’ve emphasized enough that if I relax my constraints my protocol’s applicability increases but I lose some useful protocol properties. Just how far can I go with relaxing my constraints? Let’s see how far the editors of Wikipedia go. They accept in the page identified by the URI <a href="http://en.wikipedia.org/wiki/Tutankhamun">http://en.wikipedia.org/wiki/Tutankhamun</a> any information about the Egyptian pharaoh that meets the quality standards of an encyclopedia. They would definitely not accept information about someone’s pet just because it happens to be named Tutankhamun and they would be equally perplexed to find information about <a title="Wikipedia article: Joe DiMaggio" href="http://en.wikipedia.org/wiki/Joe_DiMaggio">Joe DiMaggio</a> at this URI. Sounds like common sense? I’ve told you that I’m demystifying the REST constraints.</p>
<p style="text-align:justify;">Let me generalize a bit. We expect both URIs and message bodies to mean something. When they are used together in HTTP, we expect their meanings to be related and this relationship between their meanings to remain the same. This is the same as to say that we don’t want to receive (or send) two HTTP message bodies with entirely different meanings from the same URI. This relaxed constraint was implicit in the first version of my protocol, which asked for strict one-to-one mapping between URI and message body. The relaxed version permits many-to-many relationship between the two as long as the relationship between the <em>meaning</em> remains one-to-one.</p>
<p style="text-align:justify;">How useful is this relaxed constraint? The full answer doesn’t fit into this post, but let’s see if we can build a SOAP-like RPC protocol without having HTTP message bodies with different meanings sent to or returned from the same URI. If our service has a single URI, the message bodies mean “invoke method A”, “invoke method B”, and so on. Even if each method has its own URI, the message body sent means “invoke the method” while the message body returned means “this is the result”. Can we say they mean the same thing? I&#8217;m not saying the constraint was explicitly formulated just to prevent us from doing RPC over HTTP, only that it has this result as well.</p>
<p style="text-align:justify;">Roy Fielding states the same constraint when he says that <em>message bodies should be representations of resources identified by URI</em>s even though the explanation some people give goes like this (I’m kidding you not): “Two of the REST constraints are the identification of resources and the manipulation of resources by representations. An identifier identifies a resource. A resource is anything that can be identified. A representation can be anything you can send over the network. Got it?” This is not what Fielding says although he says all these things. Each sentence is a quote from his dissertation, but taken out of context, combined into a meaningless blurb, and passed on as REST design wisdom. I won’t attempt to untangle this mess. The dissertation is available online, read at least <a title="REST Architectural Elements" href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_2">section 5.2</a>.</p>
<p style="text-align:justify;">Fielding’s REST constraints are neither laws of nature nor religion. Following them does not guarantee success and violating them does not bring inevitable doom. They play the same role as “Stay on trails” signs in our national parks. If you stray from the beaten path there is a slight chance you will discover something wonderful nobody saw before, but you also risk falling into a ravine, starting an avalanche, or being killed by a grizzly bear.</p>
<p><a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license"><img style="border-width:0;" src="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" alt="Creative Commons Licence" /></a><br />
This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license">Creative Commons Attribution-ShareAlike 2.5 Canada License</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/theamiableapi.wordpress.com/990/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/theamiableapi.wordpress.com/990/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=990&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://theamiableapi.com/2012/05/06/demystifying-rest-constraints/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/303e6ea7b124c9de9baf2f23b18af19c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fmihaly</media:title>
		</media:content>

		<media:content url="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" medium="image">
			<media:title type="html">Creative Commons Licence</media:title>
		</media:content>
	</item>
		<item>
		<title>Message Encoding in REST</title>
		<link>http://theamiableapi.com/2012/04/16/message-encoding-in-rest/</link>
		<comments>http://theamiableapi.com/2012/04/16/message-encoding-in-rest/#comments</comments>
		<pubDate>Mon, 16 Apr 2012 18:01:15 +0000</pubDate>
		<dc:creator>Ferenc Mihaly</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://theamiableapi.com/?p=940</guid>
		<description><![CDATA[The basic HTTP message framing described in my last post has some performance issues. You can think of advanced message framing techniques like chunking, compression, and multipart messages as performance optimizations. The HTTP specification calls them encodings because they alter (encode) the message body for transmission and reconstruct it at arrival. All HTTP 1.1 libraries [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=940&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p style="text-align:justify;">The basic HTTP message framing described in my <a title="Message Framing in REST" href="http://theamiableapi.com/2012/04/01/message-framing-in-rest/">last post</a> has some performance issues. You can think of advanced message framing techniques like <em>chunking</em>, <em>compression</em>, and <em>multipart messages</em> as performance optimizations. The HTTP specification calls them <em>encodings</em> because they alter (encode) the message body for transmission and reconstruct it at arrival. All HTTP 1.1 libraries and frameworks support chunkig, most support compression, and many can handle multipart messages too.</p>
<h3>Chunking</h3>
<p style="text-align:justify;">You need to know the length of the message body to use the Content-Length header. While this is not an issue with static content like HTML files, it creates performance problems with dynamically generated REST messages. Not only that the entire message body has to be buffered in memory, but the network sits unused during message generation and the CPU is idle during transmission. The performance improves significantly if the two steps are combined and message generation or processing is done in parallel with transmission. To support this, a new message length prefixing model, called <a title="Wikipedi article: Chunked Transfer Encoding" href="http://en.wikipedia.org/wiki/Chunked_transfer_encoding">chunked transfer encoding</a>, was introduced in HTTP 1.1. It is described in <a title="RFC 2616: HTTP 1.1 specification" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6">RFC 2616, section 3.6.1</a></p>
<p style="text-align:justify;">Chunked transfer encoding is length prefixing applied not to the entire message body, but to smaller parts of it (chunks). A chunk starts with the length of data in hexadecimal format separated by a CRLF (carriage return and line feed) sequence from the actual chunk data. Another CRLF pair marks the end of the chunk. After a series of chunks a zero-length chunk signals the end of the message. The presence of the <a title="The Transfer-Encoding HTTP header" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.41">Transfer-Encoding</a> header containing the value “chunked” and the absence of the <a title="The Content-Lenght HTTP header" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13">Content-Length</a> header tell the receiver to read the message body in chunks (Figure 1).</p>
<div id="attachment_963" class="wp-caption aligncenter" style="width: 514px"><a href="http://theamiableapi.files.wordpress.com/2012/04/chunked-and-compressed-message1.png"><img class=" wp-image-963 " title="Figure 1: Compressed and chunked HTTP response" src="http://theamiableapi.files.wordpress.com/2012/04/chunked-and-compressed-message1.png?w=504&#038;h=241" alt="Figure 1: Compressed and chunked HTTP response" width="504" height="241" /></a><p class="wp-caption-text">Figure 1: Compressed and chunked HTTP response</p></div>
<p style="text-align:justify;">You don’t need to take any action to enable chunking. Basic message framing is used only for short messages. Longer messages are automatically chunked by HTTP 1.1 implementations. Just remember not to depend on the Content-Length header for message processing because it is not always present. Structure your code so that you can begin processing before receiving the full message body. Use streaming and event-based programming techniques, for example event-based JSON and XML parsers.</p>
<h3>Compression</h3>
<p style="text-align:justify;">Compression is a data optimization technique used to reduce message sizes, thus network bandwidth usage. It also speeds up message delivery. Compression looks for repeating patterns in data streams and replaces their occurrences with shorter placeholders. How effective this is depends on the type and volume of data. XML and JSON compress quite well, by 60% or more for messages over two kilobytes in length. <a title="JSON compression algorithm comparison" href="http://web-resource-optimization.blogspot.ca/2011/06/json-compression-algorithms.html">Experience shows</a> that the generic HTTP compression algorithms are just as effective as specially developed JSON- and XML-aware algorithms.</p>
<p style="text-align:justify;">HTTP compresses the message body before sending it and un-compresses it at arrival. Headers are never compressed. If present, the Content-Length header shows the number of the actual (compressed) bytes sent. Similarly, chunking is applied to the already compressed stream of bytes (Figure 1). Since compression is optional in HTTP 1.1, clients must list the compression algorithms they support in the <a title="The Accept-Encoding HTTP header" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3">Accept-Encoding</a> header to receive compressed messages. Likewise, REST services should not send compressed content unless the client is prepared to receive it. Compressed messages are sent with a <a title="The Content-Encoding HTTP header" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11">Content-Encoding</a> header identifying the compression algorithm used.</p>
<p style="text-align:justify;">Client support for HTTP compression is good since well-known public domain algorithms are used. On Android, you can receive gzip compressed messages with the <a title="Spring for Android RestTemplate Module" href="http://static.springsource.org/spring-android/docs/1.0.x/reference/html/rest-template.html">Spring for Android RestTemplate Module</a>. <a title="Does RestKit support GZip?" href="https://github.com/RestKit/RestKit/issues/511">RestKit for Apple iOS</a> is built on top of NSURLConnection, which provides transparent gzip/deflate support for response bodies. On Blackberry you can use <a title="javax.microedition.io.HttpConnection " href="http://www.blackberry.com/developers/docs/4.0.2api/javax/microedition/io/HttpConnection.html">HttpConnection</a> with with <a title="net.rim.device.api.compress.GZIPInputStream" href="http://www.blackberry.com/developers/docs/4.2api/net/rim/device/api/compress/GZIPInputStream.html">GZipInputStream</a>. When writing client-side Javascript the XmlHttpRequest implementation decompresses messages automatically.</p>
<h3>Multipart messages</h3>
<p style="text-align:justify;">As the name suggests, multipart messages contain parts of different types within as a single message body. This helps reduce protocol chattiness, eliminating the need to retrieve each part with a separate HTTP request. In REST this technique is called <em>batching</em>.</p>
<div id="attachment_959" class="wp-caption aligncenter" style="width: 514px"><a href="http://theamiableapi.files.wordpress.com/2012/04/multipart-message1.png"><img class=" wp-image-959 " title="Figure 2: Multipart HTTP response" src="http://theamiableapi.files.wordpress.com/2012/04/multipart-message1.png?w=504&#038;h=533" alt="Figure 2: Multipart HTTP response" width="504" height="533" /></a><p class="wp-caption-text">Figure 2: Multipart HTTP response</p></div>
<p style="text-align:justify;">Multipart encoding was originally developed for email attachments (Multipurpose Internet Mail Extensions or MIME) and later extended to HTTP and the Web. It is described in six related RFC documents: <a title="Multipurpose Internet Mail Extensions (MIME) Part One" href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>, <a title="  Multipurpose Internet Mail Extensions (MIME) Part Two" href="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</a>, <a title="MIME (Multipurpose Internet Mail Extensions) Part Three" href="http://www.ietf.org/rfc/rfc2047.txt">RFC 2047</a>, <a title="Media Type Specifications and Registration Procedures" href="http://www.ietf.org/rfc/rfc4288.txt">RFC 4288</a>, <a title="Multipurpose Internet Mail Extensions (MIME) Part Four:" href="http://www.ietf.org/rfc/rfc4289.txt">RFC 4289</a> and <a title="Multipurpose Internet Mail Extensions  (MIME) Part Five:" href="http://www.ietf.org/rfc/rfc2049.txt">RFC 2049</a>. Figure 2 shows a multipart message example. To receive multipart messages, clients must list the multipart formats they support in the Accept header. The Content-Type header identifies the type of multipart message sent (related, mixed, etc.) and also contains the byte pattern used to mark the boundary between message parts. The mime type of each message part is transmitted separately as shown in Figure 2.</p>
<p style="text-align:justify;">Building and parsing multipart messages is difficult unless supported out-of-the box by libraries or frameworks. You cannot expect clients to write code for it from scratch so you must provide alternative ways of retrieving the data. Common alternatives are embedding links into messages to let clients retrieve parts separately or using JSON or XML collections for embedding multiple message parts of the same type.</p>
<p style="text-align:justify;">REST message examples are always shown in documentation with basic message framing because it is easy to read. Nonetheless, many real-life REST protocols use a combination of chunking, compression, and multipart encoding for better performance. When you develop REST clients, remember that compression and multipart encoding are optional. REST services won’t use them unless the client sends them the proper Accept and Accept-Encoding headers. When you design REST services, consider compressing large messages to save bandwidth and using multipart messages to reduce protocol chattiness.</p>
<p><a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license"><img style="border-width:0;" src="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" alt="Creative Commons Licence" /></a><br />
This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license">Creative Commons Attribution-ShareAlike 2.5 Canada License</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/theamiableapi.wordpress.com/940/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/theamiableapi.wordpress.com/940/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=940&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://theamiableapi.com/2012/04/16/message-encoding-in-rest/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/303e6ea7b124c9de9baf2f23b18af19c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fmihaly</media:title>
		</media:content>

		<media:content url="http://theamiableapi.files.wordpress.com/2012/04/chunked-and-compressed-message1.png" medium="image">
			<media:title type="html">Figure 1: Compressed and chunked HTTP response</media:title>
		</media:content>

		<media:content url="http://theamiableapi.files.wordpress.com/2012/04/multipart-message1.png" medium="image">
			<media:title type="html">Figure 2: Multipart HTTP response</media:title>
		</media:content>

		<media:content url="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" medium="image">
			<media:title type="html">Creative Commons Licence</media:title>
		</media:content>
	</item>
		<item>
		<title>Message Framing in REST</title>
		<link>http://theamiableapi.com/2012/04/01/message-framing-in-rest/</link>
		<comments>http://theamiableapi.com/2012/04/01/message-framing-in-rest/#comments</comments>
		<pubDate>Sun, 01 Apr 2012 20:20:41 +0000</pubDate>
		<dc:creator>Ferenc Mihaly</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Interface]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://theamiableapi.com/?p=887</guid>
		<description><![CDATA[Most REST designers take message framing for granted; something they get for free from HTTP and don’t need to worry about because it just works. You are probably wondering what motivated me to write about such an obvious and unimportant topic. I wanted to show that REST exposes message framing details to clients. This can [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=887&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p style="text-align:justify;">Most REST designers take message framing for granted; something they get for free from HTTP and don’t need to worry about because it just works. You are probably wondering what motivated me to write about such an obvious and unimportant topic. I wanted to show that REST exposes message framing details to clients. This can cause some issues and may influence your REST design decisions.</p>
<h3>The need for message framing</h3>
<p style="text-align:justify;">That you cannot send messages directly over TCP is the first difficulty in application protocol design. There is no “send message” function. You read from an input stream by calling a &#8220;receive&#8221; method, and you write to an output stream by calling a &#8220;send&#8221; method. However, you cannot assume that a single &#8220;send&#8221; will result in a single &#8220;receive&#8221;. Message boundaries are not preserved in TCP.</p>
<p style="text-align:justify;">HTTP uses a combination of <a title="TCP Message Framing Techniques" href="http://www.codeproject.com/Articles/37496/TCP-IP-Protocol-Design-Message-Framing">message framing techniques</a>, delimiters and prefixing, to send messages over TCP (Figure 1).</p>
<div id="attachment_905" class="wp-caption aligncenter" style="width: 469px"><a href="http://theamiableapi.files.wordpress.com/2012/03/message.png"><img class=" wp-image-905     " title="Figure 1: HTTP message framing" src="http://theamiableapi.files.wordpress.com/2012/03/message.png?w=459&#038;h=179" alt="Figure 1: HTTP message framing" width="459" height="179" /></a><p class="wp-caption-text">Figure 1: HTTP message framing</p></div>
<p style="text-align:justify;"><strong>Delimiters</strong> are predetermined markers placed inside and around messages to help the protocol separate messages and message parts from each other when reading from an input stream. The carriage return &#8211; new line (/r/n) pair of characters divide the ASCII character stream of the HTTP message header into lines. Another delimiter, white space, divides the request and status lines into sections. A third delimiter, the colon, separates header names from header values. An empty line marks the end of the header and the beginning of the (optional) message body.</p>
<p style="text-align:justify;"><strong>Prefixing</strong> works by sending in the first part of messages information about the remaining, variable part. HTTP uses headers for prefixing, instructing the protocol implementation how to handle the message body. Length prefixing is the most important: the <a title="The Content-Lenght HTTP header" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13">Content-Length</a> header tells the protocol implementation how many bytes to read before it reaches the end of the message body.</p>
<p style="text-align:justify;">The message framing details are clearly visible when you look at REST messages (Figure 1) and are also partially exposed in code that generates them (Listing 1).</p>
<h3>Not a text-based protocol</h3>
<p style="text-align:justify;">That HTTP is a text-based protocol is a widespread misconception. Only the header section is sent as ASCII characters, the message body is sent as a sequence of bytes. This has the consequence that sending text in the message body is not quite as straightforward as you might expect. You need to ensure that both client and server use the same method when converting text to bytes and back.</p>
<p style="text-align:justify;">It is much safer to be explicit about the character set used by setting and reading the character set from the <a title="The Accept HTTP header" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">Accept</a>, <a title="The Accept-Charset HTTP header" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2">Accept-Charset</a>, and <a title="The Content-Type HTTP header" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> headers than relying on defaults. Client libraries and server frameworks are partially to blame for the text-based protocol misconception because they attempt to convert text using a default character set. The Apache client library uses ISO-8859-1 by default as required by <a title="RFC 2616: HTTP 1.1 specification" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1">RFC2616 section 3.7.1</a>, but this obviously can cause problems if the server is sending JSON using UTF-8.</p>
<p><strong>Listing 1: Sending a text message to a URL in Java using the Apache HTTP client library</strong></p>
<pre>    /**
     * Sends a text message to the given URL
     * @param message the text to send
     * @param url where to send it to
     * @return true if the message was sent, false otherwise
     **/
    public static boolean sendTextMessage(String message, String url) {
        boolean success = false;
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpPost request = new HttpPost(url);

            BasicHttpEntity entity = new BasicHttpEntity();
            byte[] content = message.getBytes("utf-8");
            entity.setContent(new ByteArrayInputStream(content));
            entity.setContentLength(content.length);
            request.setEntity(entity);
            request.setHeader("Content-Type", "text/plain; charset=utf-8");

            HttpResponse response = httpClient.execute(request);

            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            success = (statusCode == 200);
        } catch (IOException e) {
            success = false;
        } finally {
           httpClient.getConnectionManager().shutdown();
        }
        return success;
    }</pre>
<h3>Restrictions on headers</h3>
<p style="text-align:justify;">The use of delimiters for message framing limits what data can be safely sent in HTTP headers. You will find these limitations in RCF 2616, <a title="Basic Rules" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2">section 2.2</a> and <a title="HTTP headers" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">section 4.2</a>, but here is a short summary:</p>
<ul>
<li>All data need to be represented as ASCII characters</li>
<li>The delimiter characters used for message framing cannot appear in header names or values</li>
<li>Header names are further limited to lowercase and uppercase letters and the dash character</li>
<li>There is also a maximum limit on the length of each header, typically 4 or 8 KB</li>
<li>It is a convention to start all custom header names not defined in RFC2616 with “X-”</li>
</ul>
<p style="text-align:justify;">You might occasionally encounter message framing errors because some client library implementations expose the headers without enforcing these rules. If a HTTP framework or intermediary detects a framing error, it discards the request and returns the &#8220;400 Bad Request&#8221; status code. What may be even worse though, every so often a malformed message will get through, causing weird behavior or a &#8220;500 Internal Error&#8221; status code and some incomprehensible internal error message. To avoid such hard-to-trace errors do not attempt to send in HTTP headers any data which:</p>
<ul>
<li>comes from user input</li>
<li>is shown to the user</li>
<li>is persisted</li>
<li>can grow in size uncapped</li>
<li>you have no full control over (it is generated by third-party libraries or services)</li>
</ul>
<h3>Keeping protocol data separate from application data</h3>
<p style="text-align:justify;">Notice that I did not say don&#8217;t use headers at all. Many REST protocols chose not to use them, but this may not be the wisest protocol design decision. Headers and body serve distinct roles in protocol design and both are important.</p>
<p style="text-align:justify;"><strong>The message header</strong> carries information needed by the protocol implementation itself. The headers tells the protocol what to do, but do not necessarily show what the application is doing. If you are sniffing the headers you are not likely to capture any business information collected and stored by an application.</p>
<p style="text-align:justify;"><strong>The message body</strong> is where the application data is sent, but it has no or very little influence on how the protocol itself works. Protocols typically don’t interpret the data sent in message bodies and treat it as opaque streams of bytes.</p>
<p style="text-align:justify;">Sending protocol data in the message body creates strong couplings between the various parts of the application, making further evolution difficult. Once I asked someone to return the URI of a newly created resource in the <a title="The Content-Location HTTP header" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.14">Content-Location</a> header of a POST response, a common HTTP practice. “There is no need”, he said, “the URI is already available as a link in the message body”. This was true, of course, but the generic protocol logic in which I needed this URI was up till then completely independent of any resource representations. Forcing it to parse the URI out of the representations meant that it will likely break the next time the representations changed.</p>
<h3>Conclusion</h3>
<p style="text-align:justify;">I hope I managed to convince you that message framing in REST is not a mere implementation detail you can safely ignore.  Becoming familiar with how it works can help you avoid some common pitfalls and design more robust REST APIs. I discussed only basic HTTP message framing so far. In my <a href="http://theamiableapi.com/2012/04/16/message-encoding-in-rest/">next post</a> I’ll talk about more advanced topics like chunking, compression, and multipart messages.</p>
<p><a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license"><img style="border-width:0;" src="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" alt="Creative Commons Licence" /></a><br />
This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license">Creative Commons Attribution-ShareAlike 2.5 Canada License</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/theamiableapi.wordpress.com/887/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/theamiableapi.wordpress.com/887/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=887&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://theamiableapi.com/2012/04/01/message-framing-in-rest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/303e6ea7b124c9de9baf2f23b18af19c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fmihaly</media:title>
		</media:content>

		<media:content url="http://theamiableapi.files.wordpress.com/2012/03/message.png" medium="image">
			<media:title type="html">Figure 1: HTTP message framing</media:title>
		</media:content>

		<media:content url="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" medium="image">
			<media:title type="html">Creative Commons Licence</media:title>
		</media:content>
	</item>
		<item>
		<title>REST Design Philosophies</title>
		<link>http://theamiableapi.com/2012/03/18/rest-design-philosophies/</link>
		<comments>http://theamiableapi.com/2012/03/18/rest-design-philosophies/#comments</comments>
		<pubDate>Mon, 19 Mar 2012 01:13:29 +0000</pubDate>
		<dc:creator>Ferenc Mihaly</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://theamiableapi.com/?p=845</guid>
		<description><![CDATA[In my previous post I said that REST is a protocol design technique. Chances are you do not agree or at least not completely. REST can be deceptively simple and frustratingly controversial at the same time. We often find ourselves in the middle of heated debates and are quickly labeled dogmatic RESTafarians or clueless, reckless [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=845&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p style="text-align:justify;">In my <a title="REST and the Art of Protocol Design" href="http://theamiableapi.com/2012/03/04/rest-and-the-art-of-protocol-design/">previous post</a> I said that REST is a protocol design technique. Chances are you do not agree or at least not completely. REST can be deceptively simple and frustratingly controversial at the same time. We often find ourselves in the middle of heated debates and are quickly labeled dogmatic RESTafarians or clueless, reckless hackers when expressing an opinion. If you don’t know what I’m talking about, read this <a title="Why understanding REST is hard" href="http://ivanzuzak.info/2010/04/03/why-understanding-rest-is-hard-and-what-we-should-do-about-it-systematization-models-and-terminology-for-rest.html">well-researched article</a> by Ivan Zuzak or better yet, join a <a title="API Craft Discussion Group" href="https://groups.google.com/forum/?fromgroups#!forum/api-craft">REST discussion group</a>.</p>
<p style="text-align:justify;">Why is REST controversial? Building distributed applications is <em>hard</em>. REST simplifies it by leveraging existing web design patterns and protocols, but many important design tradeoffs remain. Designers resolve tradeoffs based on what they consider important. What is important is not simply a matter of personal opinion, but depends on the kind of application you are building. So instead of best practices everybody agrees on REST has a number of distinct schools of thought or design philosophies; neither inherently good nor bad, neither obviously right nor wrong; each with its champions and detractors.</p>
<p style="text-align:justify;">I’ll attempt to describe four of these design philosophies without claiming any authority in the matter. Others would likely name and describe them differently. I decided to draw quick sketches instead of painting full portraits, capturing the distinctive features and worrying less about getting every detail right.</p>
<h3>Hypermedia APIs</h3>
<p style="text-align:justify;">This design philosophy admires and tries to replicate the properties of the World Wide Web as a distributed application development platform. Its proponents believe that the phenomenal success of the Web is due to a number of high-level design choices which together define what they call its <em>architectural style</em>. <a title="Roy Fielding: Architectural Styles and the Design of Network-based Software Architectures" href="http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm">Roy Fielding</a> was the first to describe this architectural style naming it <strong>RE</strong>presentational <strong>S</strong>tate <strong>T</strong>ransfer or REST. For this reason many consider it the only “true” definition of REST.</p>
<p style="text-align:justify;">The single most distinctive feature of this design philosophy is the use of <em>hypermedia</em> or HTTP messages with embedded hyperlinks, hence the name. The links guide clients to discover available resources and operations dynamically. While specific URIs patterns are used, clients are not expected to understand them and are actively discouraged from parsing or building URIs. You can get a better understanding of how Hypermedia APIs are designed and how they work watching Jon Moore build one in this <a title="JonMoore: Hypermedia APIs" href="http://oredev.org/2010/sessions/hypermedia-apis">video</a>.</p>
<p style="text-align:justify;">Much of the Hypermedia API discussion focuses on the difficult task of writing complex, large-scale distributed applications and on evolving them over decades. Design attributes like scalability and loose coupling are considered much more important than simplicity and ease of use. This discourages some who claim that while they understand Hypermedia APIs in theory, they find them difficult to use in practice.</p>
<h3>Data APIs</h3>
<p style="text-align:justify;">If Hypermedia APIs are an architectural style, Data APIs are first and foremost an <em>application integration pattern</em>. Its proponents consider <em>standardization</em> as the most important design goal, believing that exposing the application’s underlying data in a standard format permits easier and more innovative integrations than exposing the application’s complex, cumbersome, and often restrictive business logic. Data APIs are published by organizations wishing to share useful data without giving access to the application which collects it or are added to existing enterprise software to facilitate third-party integrations.</p>
<p style="text-align:justify;">Data APIs use the HTTP methods POST/GET/PUT/DELETE strictly as the CRUD operations Create/Read/Update/Delete. If they expose any application logic at all, they expose it implicitly. For example, if you use a Data API to manipulate purchase orders you obviously expect that products will be shipped and people billed as a result, but this has no direct effect on how the API looks or works. The behavior is simply implied by our shared understanding of what a purchase order is.</p>
<p style="text-align:justify;">The URI structure is standardized and client applications are encouraged to use URI templates for building queries similar to SQL select statements. The format in which the data is returned is also standardized, often based on the ATOM format. For an example of a standardized Data API take a closer look at <a title="Open Data Protocol Home Page" href="http://www.odata.org/">Microsoft’s Open Data Protocol</a>.</p>
<h3>Web APIs</h3>
<p style="text-align:justify;">The designers of Web APIs consider achieving large-scale <em>developer adoption</em> as the most important API design challenge. They try to drive adoption by aiming for the <em>widest possible platform support</em> and maintaining a <em>very low barrier of entry</em>.</p>
<p style="text-align:justify;">It is only a slight exaggeration to say that if a feature is not guaranteed to work in Adobe Flash, on an underpowered mobile phone, on a remote Pacific island, through a web proxy, and from behind an ancient firewall from the 90’s, Web API designers won’t use it. If an interface cannot be accessed directly from HTML forms or called by writing less than five lines of JavaScript, Web API designers worry about adoption.</p>
<p style="text-align:justify;">The result is that Web APIs manage to get by using a surprisingly small subset of features. They stick to GET and POST, largely eschew HTTP headers, strongly favor JSON over XML, and rarely use hyperlinks. Information is often passed in URLs, because “URLs are easy to type into the address bar of a browser”. I call them Web APIs because I see this pattern in services offered to developers at large over the Internet (often free of charge) and are primarily used in Web Mashups or equivalent mobile apps. Many of the smaller, simpler APIs listed in the <a title="Programmable Web API Directory" href="http://www.programmableweb.com/apis/directory/1?sort=category">Programmable Web API Directory</a> are Web APIs. Perhaps the best known and most frequently imitated is the <a title="Twitter API online documentation" href="https://dev.twitter.com/docs/api">Twitter API</a>.</p>
<h3>Pragmatic REST APIs</h3>
<p style="text-align:justify;">Pragmatists believe that design trade-offs should be resolved based on concrete, project-specific requirements and constraints. They view the indiscriminate application of the same design patterns to widely different problems as a sign of dogmatic thinking, not as disciplined design. Absent specific requirements and constraints, pragmatists prefer to use the simplest possible design. What “simplest” means is again very context dependent. It may mean a design which fits the technologies, frameworks, or tools used the best.</p>
<p style="text-align:justify;">You might argue that Pragmatic REST is not a separate design philosophy since its practitioners freely borrow and mix design approaches from all the other schools. The “pragmatic” label best describes APIs which do not fit neatly into any of the other categories. There are quite a few of these. If you look at the <a title="Google API Explorer" href="http://code.google.com/apis/explorer/">collection of the Google APIs</a> you will discover characteristics of Hypermedia APIs, Data APIs, and Web APIs, but not in their purest forms.</p>
<h3 style="text-align:justify;">In Lieu of Conclusion</h3>
<p style="text-align:justify;">If memory serves me well, the Big REST Debate reached its peak sometime around 2008.  The rhetoric cooled since, largely because the protagonists agreed to disagree, do REST their own way, and mostly ignore each other. But the issue is far from being settled and I doubt it will ever be. When I decided to illustrate the principles and methods of protocol design using REST, I knew that I can&#8217;t pretend not to notice the elephant in the room. That&#8217;s why I wrote this post.  In my <a title="Message Framing in REST" href="http://theamiableapi.com/2012/04/01/message-framing-in-rest/">next post</a> I&#8217;ll return to talk about REST and protocol design.</p>
<p><a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license"><img style="border-width:0;" src="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" alt="Creative Commons Licence" /></a><br />
This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license">Creative Commons Attribution-ShareAlike 2.5 Canada License</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/theamiableapi.wordpress.com/845/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/theamiableapi.wordpress.com/845/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=845&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://theamiableapi.com/2012/03/18/rest-design-philosophies/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/303e6ea7b124c9de9baf2f23b18af19c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fmihaly</media:title>
		</media:content>

		<media:content url="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" medium="image">
			<media:title type="html">Creative Commons Licence</media:title>
		</media:content>
	</item>
		<item>
		<title>REST and the Art of Protocol Design</title>
		<link>http://theamiableapi.com/2012/03/04/rest-and-the-art-of-protocol-design/</link>
		<comments>http://theamiableapi.com/2012/03/04/rest-and-the-art-of-protocol-design/#comments</comments>
		<pubDate>Sun, 04 Mar 2012 22:45:57 +0000</pubDate>
		<dc:creator>Ferenc Mihaly</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Interface]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Usability]]></category>

		<guid isPermaLink="false">http://theamiableapi.com/?p=790</guid>
		<description><![CDATA[RESTful protocol design is a topic more appropriate for a book than a blog post. Despite the catchy title my goal is very modest. I would like to show you that even limited protocol design knowledge can help you understand the essence of REST and the reasoning behind many of its best practices. I’ll start [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=790&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p style="text-align:justify;">RESTful protocol design is a topic more appropriate for a book than a blog post. Despite the catchy title my goal is very modest. I would like to show you that even limited protocol design knowledge can help you understand the essence of REST and the reasoning behind many of its best practices.</p>
<p style="text-align:justify;">I’ll start with a <a title="Wikipedia: Basic requirements of protocols" href="http://en.wikipedia.org/wiki/Communications_protocol#Basic_requirements_of_protocols">core insight from protocol design</a>, which is that <em>programs need to share pre-existing knowledge to communicate</em>. Without knowing how to separate incoming messages (framing), convert bytes to useful internal representations (decoding), generate correct sequences of messages to accomplish tasks (state machines), and detect and respond to error conditions, programs only see meaningless streams of bytes. Roy Fielding, who coined the term REST, <a title="Royr Fielding's comment on the use of hypermedia" href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-742">said</a>: <em>“Of course the client has prior knowledge. Every protocol, every media type definition, every URI scheme, and every link relationship type constitutes prior knowledge that the client must know (or learn) in order to make use of that knowledge.”</em></p>
<p style="text-align:justify;">What method to use to establish the shared pre-existing knowledge is one of the most fundamental protocol design decisions.</p>
<p style="text-align:justify;">The RESTful method is to minimize the need for <em>new</em> (application-specific) knowledge by reusing the <em>existing</em> knowledge of ubiquitous, mature, and stable web protocols. New RESTful application protocols are designed by constraining and further specifying another application protocol, the HTTP protocol. Every REST message is also a valid HTTP message and can be processed with existing HTTP client libraries, browsers, firewalls, web proxies, and server-side web application frameworks. Simple RESTful applications need very little new code at the protocol layer because so much of this code is reused.</p>
<p style="text-align:justify;">It is important to point out that RESTful protocol design fully leverages HTTP as an application protocol, which is fundamentally different from what other HTTP-based protocols do. SOAP is conceived as a protocol layer above HTTP and uses it as a transport protocol. SOAP needs formal WSDL for protocol description and complex code generation tools in part because it does not reuse any of the application protocol features of HTTP. Other protocols like WebDAV extend HTTP with new methods and headers. While such protocol extensions were anticipated in the HTTP specification, many practical difficulties arise when generic HTTP libraries, intermediaries, or frameworks fail to understand the newly added features. WebDAV does not work well over the Internet and failed to see wide-scale adoption. This is why RESTful protocol design avoids the use of HTTP protocol extensions.</p>
<p style="text-align:justify;">A frequently cited example of a carefully designed RESTful protocol is the Atom Publishing Protocol described in <a title="RFC 5023: The Atom Publishig Protocl" href="http://www.ietf.org/rfc/rfc5023.txt">RFC 5023</a>. You can tell that it leverages and constrains HTTP as an application protocol after seeing the HTTP specification explicitly referenced 18 times, in sentences like “Any server response or server content modification not explicitly forbidden by this specification or HTTP [RFC2616] is therefore allowed”.</p>
<p style="text-align:justify;">Reusing existing web protocols has many advantages. First among them is a very low barrier of entry and implicit support for a large variety of platforms. Visibility, or the ability of third parties to see and interact with the protocol and provide useful services, is another. Web protocols are extremely stable and resilient, to the point that in 2011 InfoQ could ran the <a title="InfoQ: 2011 April's fool day article" href="http://www.infoq.com/news/2011/04/http-1.2-released">fake news of the release of the HTTP/1.2 </a>as an April’s Fools Day joke. They evolve and combine well thanks to a clever design which fully decouples the concerns of addressing, operations, and representations. Web applications are the best illustration of just how beneficial loose coupling is: you can run all of them in the same generic client, a web browser, without adding or modifying a single line of code.</p>
<p style="text-align:justify;">There is, however, an important <em>difficulty</em>. You cannot use existing protocols as pre-existent knowledge <em>unless you use them precisely as they were meant to be used</em>. Protocol visibility means that server-side frameworks, network intermediaries, and client libraries read and interpret HTTP methods, status codes, and headers and automatically take specific actions, like closing the TCP connection, caching content, or clearing caches. They stop working correctly if you do something unexpected. It is good to know that when people insist on the <em>correct</em> way of doing RESTful protocol design, what they talk about is more than just a personal opinion.</p>
<p style="text-align:justify;">What else do I mean by using web technologies the way they were meant to be used? Ideally, I would like to see all RESTful protocols work with a single generic client like a web browser. Before you jump to any conclusions, let me state that compatibility with browsers is not an <em>actual</em> REST requirement. However, the further away you move from this ideal, the more application-specific knowledge you’ll need to hard-wire into your programs. And, as I said, minimizing application-specific knowledge is at the very core of RESTful protocol design philosophy. This is again good to know, because many common REST best practices directly derive from it.</p>
<p style="text-align:justify;">A practical advice immediately follows from the above discussion, namely that before taking the plunge into RESTful protocol design it is a good idea to study and understand the underlying web technologies. This is not an effortless undertaking. The <a title="RFC 2616: HTTP 1.1 specification " href="http://www.ietf.org/rfc/rfc2616.txt">HTTP 1.1 specification (RFC 2616)</a> alone is 176 pages long, with enough subtleties to justify the publication of <a title="David Gourley: HTTP - The definitive Guide" href="http://www.amazon.com/HTTP-Definitive-Guide-David-Gourley/dp/1565925092">several</a> <a title="Christ Shiflett: HTTP Developer's Handbook" href="http://www.amazon.com/HTTP-Developers-Handbook-Chris-Shiflett/dp/0672324547/">popular</a> <a title="Stephen Thomas: HTTP Essentials - Protocols for Secure, Scaleable Web Sites" href="http://www.amazon.com/HTTP-Essentials-Protocols-Secure-Scaleable/dp/0471398233/">books</a>. URIs are not just strings, but also a set of rules, described in the 40 page long <a title="RFC 2396: Uniform Resource Identifiers (URI)" href="http://www.ietf.org/rfc/rfc2396.txt">RCF 2396</a>. Another 43 pages in <a title="RFC 2046: Multipurpose Internet Mail Extensions" href="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</a> specify the MIME media types used in HTTP requests and responses and we haven’t even talked yet about XML, for which a <a title="W3C: Extensible Markup language (XML)" href="http://www.w3.org/XML/">entire set of specifications</a> is maintained by the W3C. Even the much simpler JSON representation has a formal specification, the 10-page <a title="RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON)" href="http://www.ietf.org/rfc/rfc4627.txt">RCF 4627</a>.</p>
<p style="text-align:justify;">I get two strong objections to the above advice.</p>
<p style="text-align:justify;">A frequent objection is this: &#8220;Why should I spend time and effort learning these protocol implementation details when I&#8217;ve already got code which handles them?&#8221; As I&#8217;ve already explained in a <a title="Challenges of Remote Interface Design" href="http://theamiableapi.com/2012/02/21/challenges-of-remote-interface-design/">previous blog post</a>, when I work with existing libraries and frameworks, I work with <a title="Joel Sposlky: The Law of leaky Abstractions" href="http://www.joelonsoftware.com/articles/LeakyAbstractions.html">leaky abstractions</a>, and, as Joel Spolsky said, &#8220;&#8230;they save us time working, but they don&#8217;t save us time learning&#8221;. I often find that I need to know the implementation details to use these abstractions correctly.</p>
<p style="text-align:justify;">Another objection is that my advice sounds like coming from someone who completely ignores such fundamental REST principles as stateless interactions, the use of uniform interfaces, or hypertext as the engine of application state (HATEOAS). This is intentional from my part. Not that the principles aren’t important, but they are also powerful abstractions and I find them difficult to understand without concrete examples. If I put building on existing protocols at the very core of my design philosophy, it makes perfect sense to me to start by learning how these protocols work. Since they are built on the same principles, learning them also makes understanding the principles a lot easier. This approach worked well for me personally, but of course, your mileage may vary.</p>
<p style="text-align:justify;">In my <a title="REST Design Philosophies" href="http://theamiableapi.com/2012/03/18/rest-design-philosophies/">next post</a> I’ll continue this topic and talk about various REST design philosophies, slightly different ways designers choose to leverage web protocols depending on which design trade-offs they consider more important.</p>
<p><a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license"><img style="border-width:0;" src="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" alt="Creative Commons Licence" /></a><br />
This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license">Creative Commons Attribution-ShareAlike 2.5 Canada License</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/theamiableapi.wordpress.com/790/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/theamiableapi.wordpress.com/790/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=790&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://theamiableapi.com/2012/03/04/rest-and-the-art-of-protocol-design/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/303e6ea7b124c9de9baf2f23b18af19c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fmihaly</media:title>
		</media:content>

		<media:content url="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" medium="image">
			<media:title type="html">Creative Commons Licence</media:title>
		</media:content>
	</item>
		<item>
		<title>API Design meets Protocol Design</title>
		<link>http://theamiableapi.com/2012/02/26/api-design-meets-protocol-design/</link>
		<comments>http://theamiableapi.com/2012/02/26/api-design-meets-protocol-design/#comments</comments>
		<pubDate>Sun, 26 Feb 2012 18:04:54 +0000</pubDate>
		<dc:creator>Ferenc Mihaly</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Interface]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Usability]]></category>

		<guid isPermaLink="false">http://theamiableapi.com/?p=742</guid>
		<description><![CDATA[In my previous post I showed that software interfaces used in distributed applications have to satisfy two conditions: should be remotely accessible should be suitable for use in high latency environments which permit partial failures, have no shared state and no reliable synchronization mechanism I also argued that technology alone – no matter which technology [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=742&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p style="text-align:justify;">In my <a title="Challenges of remote interface design" href="http://theamiableapi.com/2012/02/21/challenges-of-remote-interface-design/">previous post</a> I showed that software interfaces used in distributed applications have to satisfy two conditions:</p>
<ol>
<li>should be remotely accessible</li>
<li>should be suitable for use in high latency environments which permit partial failures, have no shared state and no reliable synchronization mechanism</li>
</ol>
<p style="text-align:justify;">I also argued that technology alone – no matter which technology you choose &#8211; only helps you with the first requirement. The concepts, principles, and methods of <em>protocol design</em> can help you meet the second condition.</p>
<p style="text-align:justify;">I&#8217;d understand if you were a bit surprised. Protocol design is indeed applicable because <em>API</em> and <em>protocol</em> are two alternative &#8211; but equally correct &#8211; ways of describing software interfaces. Wikipedia defines <a title="Wikipedia entry: Application Programming Interface" href="http://en.wikipedia.org/wiki/API">API</a> as “… a particular set of rules and specifications that software programs can follow to communicate with each other” and <a title="Wikipedia entry: Communications protocol" href="http://en.wikipedia.org/wiki/Communications_protocol">protocol</a> as “… a formal description of digital message formats and the rules for exchanging those messages in or between computing systems and in telecommunications.” We certainly tend to focus more on programming language constructs like<em></em> <em>methods</em> with <em>parameters</em> when describing APIs and on <em>processes</em> exchanging <em>messages</em> when describing protocols, but ultimately these concepts describe, from a different point of view, how programs communicate with each other.</p>
<p style="text-align:justify;">Consider the familiar real-time stock quote service as an example. We can describe it equally well by showing its API in a programming language (here, in Java):</p>
<p><strong>Listing 1: Java client library interface<br />
</strong></p>
<pre>/**
* My sample real time stock quotes service
**/
public interface StockQuotes {

   /**
   * Returns a stock quote
   * @param ticker is the symbol of the stock
   * @return the current price of the stocks
   * @throws RemoteException if there is a communication error
   **/
   public float getQuote(String ticker) throws RemoteException;
}</pre>
<p style="text-align:justify;">or by showing the messages (requests) it accepts and replies it provides (in our case, a simple RESTful protocol)</p>
<p><strong>Listing 2: REST request and reply</strong></p>
<pre>GET /quote/?ticker=AAPL HTTP/1.1
Host: StockQuotes.com
Accept: application/json</pre>
<p><em>returns</em></p>
<pre>HTTP/1.1 200 OK
Date: Fri, 17 Feb 2012 16:59:59 GMT
Content-Type: application/json
Content-Length: 29

{“ticker”:”AAPL”,
“price”:512.68}</pre>
<p style="text-align:justify;">The API description feels more natural when working via a client library while the description of the HTTP messages is useful for accessing the service from exotic environments (say Adobe Flash or SAP’s ABAP) for which no client library is provided. The same functionality could be also described as a SOAP Web Service with the following <a title="W3Schools: Introduction to WSDL" href="http://www.w3schools.com/wsdl/wsdl_intro.asp">WSDL</a>:</p>
<p><strong>Listing 3: WSDL description<br />
</strong></p>
<pre>&lt;?xml version="1.0"?&gt;
&lt;definitions name="StockQuoteServiceDefinitions"&gt;
   &lt;!-- Namespace declarations omitted for brevity --&gt;
   &lt;message name="GetQuoteRequest"&gt;
      &lt;part name="ticker" type="xsd:string"/&gt;
   &lt;/message&gt;
   &lt;message name="GetQuoteResponse"&gt;
      &lt;part name="price" type="xsd:float"/&gt;
   &lt;/message&gt;
   &lt;portType name="StockQuotePortType"&gt;
      &lt;operation name="getQuote"&gt;
         &lt;input message="tns:GetQuoteRequest"/&gt;
         &lt;output message="tns:GetQuoteResponse"/&gt;
      &lt;/operation&gt;
   &lt;/portType&gt;
   &lt;binding name="DefaultBinding" type="tns:StockQuotePortType"&gt;
      &lt;!-- Details of document literal binding style omitted for brevity --&gt;
   &lt;/binding&gt;
   &lt;service name="StockQuoteService"&gt;
      &lt;documentation&gt;My sample real time stock quote service&lt;/documentation&gt;
      &lt;port name="StockQuotePort" binding="tns:DefaultBinding"&gt;
         &lt;soap:address location="http://www.StockQuotes.com/quote/"&gt;
      &lt;/port&gt;
   &lt;/service&gt;
&lt;/definitions&gt;</pre>
<p style="text-align:justify;">Frameworks like Microsoft’s <a title="MSDN: WCF bindings in depth" href="http://msdn.microsoft.com/en-us/magazine/cc163394.aspx">WCF</a> or Java’s <a title="IBM: Developing a JAX-WS client from a WSDL file" href="http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=%2Fcom.ibm.websphere.wsfep.multiplatform.doc%2Finfo%2Fae%2Fae%2Ftwbs_jaxwsclientfromwsdl.html">JAX-WS</a> can automatically generate a client library (called a binding) from this description. The generated code looks just like a regular API to the caller, but implements its functionality by making XML (SOAP) requests over HTTP to a server. It would be pointless to debate whether this WSDL describes an API or a protocol. To support automatically generated client bindings it has to describe both.</p>
<p style="text-align:justify;">You might wonder: if API and protocol are equally appropriate for describing software interfaces, why is it that expressions like “Web Services API”, “SOAP API”, “RESTful API”, “Web API”, “Hypermedia API”, or  “Mobile API” are commonplace while few people ever talk about protocols? I don’t claim to know the answer. I can only tell you why I also frequently use the word API when I actually mean protocol.</p>
<p style="text-align:justify;">I’ve noticed that the term protocol is very closely associated with ubiquitous low-level <em>transport</em> protocols like TCP/IP and I’m often concerned that it is not immediately obvious that I’m talking about high-level <em>application</em> protocols like SMTP, HTTP, Atom or LDAP. Since the latter are used just like APIs to build client applications for accessing email, browsing the web, reading news, or looking up someone’s phone number in a corporate directory, I simply call them APIs. It is technically correct and unlikely to be misunderstood. It is certainly more convenient than spelling out “application protocol” every time.</p>
<p style="text-align:justify;">I also sometimes worry that developers may think I want them to write a ton of code, parse complex messages, and handle complex interaction patterns. If they had a <a title="Robin Sharp: Principles of Protocol Design (Amazon.com)" href="http://www.amazon.com/Principles-Protocol-Design-Robin-Sharp/dp/364209628X/">college course on protocols</a>, they were probably thought about <a title="TCP/IP Protocol Design - Message Framing " href="http://www.codeproject.com/Articles/37496/TCP-IP-Protocol-Design-Message-Framing">message framing</a>, byte stuffing, and many other low level details. This is not what I typically mean. Protocols are rarely built from scratch. They are layered on top of existing protocols, extend existing protocols, or constrain (further specify) existing protocols. Plus we have all the various tools. I use the word API in casual conversations to convey a subtle &#8220;this is not as hard as you might think&#8221; message.</p>
<p style="text-align:justify;">Just to be clear, I’m not saying that <em>calling</em> your remote interface an API is a mistake. It is not. My point is that <em>thinking</em> of it as an application protocol is helpful, especially when you are designing it. It is helpful because it forces you to take the differences between local and remote communication seriously.</p>
<p style="text-align:justify;">When I think in terms of requests and replies instead of function calls, it is hard for me to ignore latency or the possibility of partial failures. When I think in terms of data sent as messages instead of objects, I have no expectations of shared state. When I think in terms of independent processes, I know that there are no reliable methods of synchronizing them. When I think in a language-neutral way, it is a lot less likely that I assume language features which may not be available to some clients or may not work remotely.</p>
<p style="text-align:justify;">The protocol viewpoint also helps me maintain realistic &#8211; some may even say skeptical &#8211; expectations about tools and technologies I’m using. I rely on them to take care of low-level protocol details and automatically generate repetitive, boilerplate code. I accept, however, that pretty much everything else is my responsibility.</p>
<p style="text-align:justify;">In my <a title="REST and the Art of Protocol Design" href="http://theamiableapi.com/2012/03/04/rest-and-the-art-of-protocol-design/">next post</a> I’ll talk about how I apply protocol design concepts, principles, and methods to the concrete case of RESTful design and how this helps me understand &#8211; and chose from &#8211; the many contradictory advice that are out there.</p>
<p><a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license"><img style="border-width:0;" src="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" alt="Creative Commons Licence" /></a><br />
This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license">Creative Commons Attribution-ShareAlike 2.5 Canada License</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/theamiableapi.wordpress.com/742/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/theamiableapi.wordpress.com/742/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=742&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://theamiableapi.com/2012/02/26/api-design-meets-protocol-design/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/303e6ea7b124c9de9baf2f23b18af19c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fmihaly</media:title>
		</media:content>

		<media:content url="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" medium="image">
			<media:title type="html">Creative Commons Licence</media:title>
		</media:content>
	</item>
		<item>
		<title>Challenges of remote interface design</title>
		<link>http://theamiableapi.com/2012/02/21/challenges-of-remote-interface-design/</link>
		<comments>http://theamiableapi.com/2012/02/21/challenges-of-remote-interface-design/#comments</comments>
		<pubDate>Tue, 21 Feb 2012 21:29:59 +0000</pubDate>
		<dc:creator>Ferenc Mihaly</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Interface]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Usability]]></category>

		<guid isPermaLink="false">http://theamiableapi.com/?p=723</guid>
		<description><![CDATA[If you listened to some middleware vendors, you’d believe that distributed applications can be easily built by making local APIs remotely accessible. Indeed, as this 10 minute video tutorial illustrates, you can do the latter by simply adding a few annotations to your code. Vendors have products to sell and their focus on promoting ease [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=723&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p style="text-align:justify;">If you listened to some middleware vendors, you’d believe that distributed applications can be easily built by making local APIs remotely accessible. Indeed, as this 10 minute <a title="Creating your first WCF service in Visual Studio 2008" href="http://www.youtube.com/watch?v=WAq_Z-dT67o">video tutorial</a> illustrates, you can do the latter by simply adding a few annotations to your code. Vendors have products to sell and their focus on promoting ease of use is not entirely surprising.</p>
<p style="text-align:justify;">The problem is that this approach does not work. It was convincingly demonstrated in classic papers like “<a title="A Critique of the Remote Procedure Call Paradigm (PDF)" href="http://www.cs.vu.nl/~ast/publications/euteco-1988.pdf">A Critique of the Remote Procedure Call Paradigm</a>” by Professors Andrew S. Tanenbaum and Robert van Renesse (1988) or more recently by Jim Waldo and his colleagues at Sun Microsystems Laboratories in “<a title="A Note on Distributed Computing (PDF)" href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.48.7969&amp;rep=rep1&amp;type=pdf">A Note on Distributed Computing</a>” (1994).</p>
<p style="text-align:justify;">A simple example will illustrate why. Consider a local FIFO task queue used in desktop applications to maintain the responsiveness of the user interface while processing computation-intensive tasks (Listing 1). The user interface thread creates and places tasks in the queue and a background thread processes them asynchronously (Listing 2).</p>
<p><strong>Listing 1:</strong></p>
<pre>/**
 * A FIFO queue of tasks to be executed by a background thread
 * Note: This queue implementation is not thread safe
 */
public class TaskQueue {

    /**
     * @return True if the the queue is empty, False otherwise
     */
    public boolean isEmpty() {...}

    /**
     * Places a task into the queue
     * @param task the task to execute
     */
    public void putTask(Task task) {...}

    /**
     * Retrieves the next task from the queue
     * @return a task to execute
     */
    public Task getTask() {...}
}</pre>
<p><strong>Listing 2:</strong></p>
<pre>/**
 * Simple client showing the use of the task queue
 */
public class Client {

    final TaskQueue queue = new TaskQueue();

    /**
     * Called when the user chooses to print from the GUI
     */
    public void onPrint() {
        Task printTask = new PrintTask();
        synchronized (queue) {
            queue.putTask(printTask);
            queue.notifyAll();
        }
    }

    /**
     * This method runs in its own thread
     * @throws InterruptedException signals the thread to exit
     */
    public void processTasks() throws InterruptedException {
        Task task;
        while (true) {
           synchronized (queue) {
               while (queue.isEmpty()) {
                  queue.wait();
             }
             task = queue.getTask();
           }
           task.run();
        }
    }
}</pre>
<p style="text-align:justify;">Let’s say that we want to move the processing of tasks to a different computer. As platform vendors would quickly point out, making the queue interface (Listing 1) remotely accessible is easily solved with a wide variety of technologies. <em>The difficult problems are latency, possibility of partial failures, lack of shared memory, and synchronization.</em></p>
<p style="text-align:justify;"><strong>Network latency</strong> degrades the performance of some API calls by orders of magnitude, rendering them practically unusable. The local queue works well because the overhead of a call to the local putTask() method is both small and predictable. If the queue is on a different computer, a remote call is neither quick nor predictable. Transient network events like packet loss or congestion may block a call for a significant time. Because it no longer prevents the user interface from freezing up, moving the queue to a server renders it useless.</p>
<p style="text-align:justify;"><strong>Partial failures</strong> lead to non-deterministic behavior and potential data loss. Assume that we kept the queue on the client to eliminate the latency issue discussed above. What happens if the network fails while the server calls the remote getTask() method? If the failure happens before the call is processed by the queue, the server can safely retry it. However, if the failure occurs after the task was removed from the queue, but before it was delivered to the server, the task is lost, and a retry will get the next task from the queue. Since we can no longer use the queue to reliably submit tasks for processing, keeping the queue on the client does not work either.</p>
<p style="text-align:justify;"><strong>Lack of shared memory</strong> means that object references, pointers, or global state cannot be handled transparently. When a task is transferred to a different computer, the question arises what to do with the other in-memory objects it references. While sometimes it makes sense to move the referenced objects with the task, just as often we needed to look up the corresponding objects on the server. No technology can automatically handle all situations correctly, meaning that unless we change our queue and task implementations, some tasks will fail to execute on a remote server.</p>
<p style="text-align:justify;"><strong>The absence of reliable remote synchronization primitives</strong> makes even relatively simple local behaviors difficult to replicate in distributed environments. The two local threads use the built-in Java synchronization primitives to communicate with each other (Listing 2). These synchronization methods do not work remotely. Server code written as shown won’t work. We need to rewrite it, perhaps polling the queue at regular intervals. But now the calls to the queue are no longer synchronized, and unless we make the queue implementation fully re-entrant, fatal data corruption will likely occur.</p>
<p style="text-align:justify;">So what all of this boils down to in the end? It shows that all technologies used to make local APIs remotely accessible <em>leak</em>. By leaking I mean that they change the API behavior. And two APIs with different behaviors are not the same API, even if they look the same. Joel Spolsky calls this the <a title="Joel Spolsky: The Law of leaky Abstractions" href="http://www.joelonsoftware.com/articles/LeakyAbstractions.html">Law of Leaky Abstractions</a>, explaining that <em>“one reason the law of leaky abstractions is problematic is that it means that abstractions do not really simplify our lives as much as they were meant to. Code generation tools which pretend to abstract out something, like all abstractions, leak, and the only way to deal with the leaks competently is to learn about how the abstractions work and what they are abstracting. So the abstractions save us time working, but they don&#8217;t save us time learning.”</em></p>
<p style="text-align:justify;">The “don’t save us time learning” part is the reason why I don’t like calling the design of remote software interfaces “API design”. While technically correct, this choice of words encourages a false and somewhat dangerous sense of familiarity and comfort. I’ve found a better concept, one which does not swipe under the rug the important issues of latency, partial failures, lack of shared memory and synchronization. I’ll talk about this concept in the <a title="API Design meets Protocol Design" href="http://theamiableapi.com/2012/02/26/api-design-meets-protocol-design/">next installment</a>.</p>
<p>&nbsp;</p>
<p><a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license"><img style="border-width:0;" src="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" alt="Creative Commons Licence" /></a><br />
This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license">Creative Commons Attribution-ShareAlike 2.5 Canada License</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/theamiableapi.wordpress.com/723/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/theamiableapi.wordpress.com/723/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=723&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://theamiableapi.com/2012/02/21/challenges-of-remote-interface-design/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/303e6ea7b124c9de9baf2f23b18af19c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fmihaly</media:title>
		</media:content>

		<media:content url="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" medium="image">
			<media:title type="html">Creative Commons Licence</media:title>
		</media:content>
	</item>
		<item>
		<title>2.1.8. Favor abstract classes over interfaces for decoupling API from implementation</title>
		<link>http://theamiableapi.com/2012/02/12/example2/</link>
		<comments>http://theamiableapi.com/2012/02/12/example2/#comments</comments>
		<pubDate>Sun, 12 Feb 2012 19:13:23 +0000</pubDate>
		<dc:creator>Ferenc Mihaly</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://theamiableapi.com/?p=717</guid>
		<description><![CDATA[Note: I’ve picked this Java API Design Checklist item to let you know that  I’ve been quietly adding similar details to the checklist and will add more in the future. To see these details, open the list (also available from the main menu at the top of the page) and click on [explain] where available. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=717&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<blockquote><p><strong>Note:</strong> I’ve picked this <a href="http://theamiableapi.com/2012/01/16/java-api-design-checklist/">Java API Design Checklist</a> item to let you know that  I’ve been quietly adding similar details to the checklist and will add more in the future. To see these details, <a href="http://theamiableapi.com/2012/01/16/java-api-design-checklist/">open the list</a> (also available from the main menu at the top of the page) and click on [<em>explain</em>] where available.</p></blockquote>
<p><strong>Rationale: </strong></p>
<p style="text-align:justify;"><a href="http://theamiableapi.com/2011/10/12/api-design-best-practice-make-it-safe/">Safety</a> and <a href="http://theamiableapi.com/2011/10/18/api-design-best-practice-plan-for-evolution/">Evolution</a>. Abstract classes can be used everywhere Java interfaces can with the limitation that a class can only extend a single (abstract) superclass while it can implement multiple interfaces. In most APIs Java’s lack of support for multiple class inheritance is not an issue because the interfaces are not intended to be implemented by clients. In these cases abstract classes are the better design choice.</p>
<p style="text-align:justify;">In Java you cannot prevent clients from implementing public interfaces. When you use an interface for a method parameter type, the compiler only guarantees that it implements the correct method signatures; you can never be sure it also implements the correct behavior. You are left with only two choices: either you perform extensive runtime checks or blindly trust the implementation, risking serious consequences, such as data corruption. Unlike interfaces, abstract classes can have code to enforce constraints on behavior. For example, you can prevent clients from extending abstract classes, check preconditions, verify postconditions, and guarantee invariants as illustrated by the examples bellow. You cannot do any of these with interfaces.</p>
<p><strong>Do this: </strong></p>
<pre>public abstract class ApiClass {

    //Package scope constructor prevents clients
    //from extending this class
    ApiClass() {}
}</pre>
<p><strong>Do this: </strong></p>
<pre>public abstract class ApiClass {

    //This public method guarantees preconditions and postconditions
    //for any abstract method implementation
    public final Collection find(String query) {
        if(query == null) {
            throw new NullPointerException("Null query parameter");
        }
        if(query.isEmpty()) {
            throw new IllegalArgumentException("Empty query parameter");
        }
        Collection result = findImplementation(query);
        if(result == null) {
            result = new ArrayList();
        }
        return result;
    }

    protected abstract Collection findImplementation(String query);
}</pre>
<p><strong>Do this: </strong></p>
<pre>public abstract class ApiClass {

    /*
    * Garanteed invariant:
    *   value != null &amp;&amp;
    *   value != this.lastModified &amp;&amp;
    *   value.before(new Date()) &amp;&amp;
    *   oldValue.before(newValue) &amp;&amp;
    *   value unchanged =&gt; class unchanged
    */
    public final Date getLastModified() {return (Date)lastModified.clone();}

    public final void anyMutatorMethod(Param param) {
        anyMutatorMethodImplementation(param);
        updateLastModified();
    } 

    protected final void updateLastModified() {
        Date newValue = new Date();
        if(lastModified.before(newValue)) {
            lastModified = newValue;
        }
    }

    protected abstract void anyMutatorMethodImplementation(Param param); 

    private Date lastModified = new Date();
}</pre>
<p><strong>Exceptions: </strong></p>
<p style="text-align:justify;">You should use abstract classes only when they are not intended for client extension. You <em>may</em> provide abstract classes for client extension, but you should not force clients to extend them, since Java does not support multiple inheritance. Use Java interfaces instead and provide abstract classes which implement them for convenience. You can see this approach used in the Java collections library, which contains pairs like <a href="http://download.oracle.com/javase/6/docs/api/java/util/Collection.html">Collection</a> and <a href="http://download.oracle.com/javase/6/docs/api/java/util/AbstractCollection.html">AbstractCollection</a>, <a href="http://download.oracle.com/javase/6/docs/api/java/util/List.html">List</a> and <a href="http://download.oracle.com/javase/6/docs/api/java/util/AbstractList.html">AbstractList</a>, and so on. Clients are encouraged to extend the abstract classes and even when they decide to implement the interfaces directly, they can use the provided abstract classes as guidance for a correct implementation.</p>
<p style="text-align:justify;">For simple interfaces, such as callbacks, there is no need to provide corresponding abstract classes.</p>
<p style="text-align:justify;">Of course, whenever possible, concrete classes are preferable to abstract classes.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/theamiableapi.wordpress.com/717/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/theamiableapi.wordpress.com/717/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=717&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://theamiableapi.com/2012/02/12/example2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/303e6ea7b124c9de9baf2f23b18af19c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fmihaly</media:title>
		</media:content>
	</item>
		<item>
		<title>What&#8217;s with the Creative Commons license?</title>
		<link>http://theamiableapi.com/2012/02/09/whats-with-the-creative-commons-license/</link>
		<comments>http://theamiableapi.com/2012/02/09/whats-with-the-creative-commons-license/#comments</comments>
		<pubDate>Thu, 09 Feb 2012 19:01:37 +0000</pubDate>
		<dc:creator>Ferenc Mihaly</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://theamiableapi.com/?p=691</guid>
		<description><![CDATA[As you might have noticed, I added a &#8220;This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 Canada License.&#8221; notice to all content on this site. What does this mean? Some of you are hosting full, abridged, or translated (hi there, in China!) versions of my posts on your own site. This notice says [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=691&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>As you might have noticed, I added a &#8220;This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license">Creative Commons Attribution-ShareAlike 2.5 Canada License</a>.&#8221; notice to all content on this site. What does this mean?</p>
<p>Some of you are hosting full, abridged, or translated (hi there, in China!) versions of my posts on your own site. This notice says that you are more than welcome to do so, provided that:</p>
<ul>
<li>You mention my name, Ferenc Mihaly, as the author</li>
<li>You provide a link back to the original content on this site</li>
</ul>
<p>Most of you are already doing this, which is appreciated. This is it, in a nutshell. And thanks for your interest!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/theamiableapi.wordpress.com/691/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/theamiableapi.wordpress.com/691/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=691&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://theamiableapi.com/2012/02/09/whats-with-the-creative-commons-license/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/303e6ea7b124c9de9baf2f23b18af19c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fmihaly</media:title>
		</media:content>
	</item>
		<item>
		<title>1.1.1. Favor placing API and implementation into separate packages</title>
		<link>http://theamiableapi.com/2012/02/06/example1/</link>
		<comments>http://theamiableapi.com/2012/02/06/example1/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 22:01:21 +0000</pubDate>
		<dc:creator>Ferenc Mihaly</dc:creator>
				<category><![CDATA[API Design]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Interface]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Usability]]></category>

		<guid isPermaLink="false">http://theamiableapi.com/?p=651</guid>
		<description><![CDATA[Note: I&#8217;ve picked this Java API Design Checklist item as an illustrative example, not because it is of a particular importance. I&#8217;ve added similar details to other checklist items as well and will add more in the future. To see such details, open the list (also available from the main menu at the top of [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=651&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<blockquote>
<p style="text-align:justify;"><strong>Note:</strong> I&#8217;ve picked this <a href="http://theamiableapi.com/2012/01/16/java-api-design-checklist/">Java API Design Checklist</a> item as an illustrative example, not because it is of a particular importance. I&#8217;ve added similar details to other checklist items as well and will add more in the future. To see such details, <a href="http://theamiableapi.com/2012/01/16/java-api-design-checklist/">open the list</a> (also available from the main menu at the top of the page) and click on [<em>explain</em>] where available.</p>
</blockquote>
<p><strong>Rationale: </strong></p>
<p style="text-align:justify;"><a href="http://theamiableapi.com/2011/09/07/api-design-best-practice-keep-it-simple/">Simplicity</a>, <a href="http://theamiableapi.com/2011/09/14/api-design-best-practice-consistency/">Consistency</a>, <a href="http://theamiableapi.com/2011/10/12/api-design-best-practice-make-it-safe/">Safety</a> and <a href="http://theamiableapi.com/2011/10/18/api-design-best-practice-plan-for-evolution/">Evolution</a>. Java only supports public and package scoped classes. You should obviously never mix public implementation classes with APIs (see <a href="http://theamiableapi.com/2012/01/16/java-api-design-checklist#cl.item.1.1.7">checklist item</a>). You can only place package scoped classes into API packages if you are certain they will be never needed in any other (implementation) package. Otherwise developers may inadvertently change their access to public, breaking the encapsulation of the API.</p>
<p style="text-align:justify;">More importantly, Java module systems like OSGi use package boundaries for additional class loader isolation, dependency management and versioning. You won&#8217;t be able to take advantage of it if you combine API and implementation into one package.</p>
<p><strong>Do this: </strong></p>
<pre>package com.company.product;

public class ApiClass {
   private ImplementationClass m;
}

package com.company.product.internal;

public class ImplementationClass {...}</pre>
<p><strong>Don&#8217;t do this: </strong></p>
<pre>package com.company.product;

public class ApiClass {

   private ImplementationClass m;
}

class ImplementationClass {...} //package scoped</pre>
<p><strong>Exceptions: </strong></p>
<p>Very rarely, a small number of package scoped classes are useful when a separate implementation package adds no benefits, only complexity.</p>
<p>&nbsp;</p>
<p><a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license"><img style="border-width:0;" src="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" alt="Creative Commons Licence" /></a><br />
This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/2.5/ca/" rel="license">Creative Commons Attribution-ShareAlike 2.5 Canada License</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/theamiableapi.wordpress.com/651/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/theamiableapi.wordpress.com/651/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=theamiableapi.com&#038;blog=25388549&#038;post=651&#038;subd=theamiableapi&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://theamiableapi.com/2012/02/06/example1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/303e6ea7b124c9de9baf2f23b18af19c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fmihaly</media:title>
		</media:content>

		<media:content url="http://i.creativecommons.org/l/by-sa/2.5/ca/88x31.png" medium="image">
			<media:title type="html">Creative Commons Licence</media:title>
		</media:content>
	</item>
	</channel>
</rss>
