REST competitors

With all the hype surrounding REST architecture. It may be tempting to think that it is the only component based architecture. However there are quite a number of other architectures that allow for remote cooperation.

Today we will see some of the most popular ones.

XML-RPC

XML-RPC stands for XML Remote Procedure Call. This standard uses XML to encode information about the behaviour to be called on the remote system.

XML is carried over HTTP and requires no special port.

The protocol is widely supported with native support in Python, PHP, Java and virtually all major languages.

As of date, it still powers the API for the popular publishing platform wordpress.

JSON-RPC

JSON-RPC is an acronym for JSON Remote Procedure Call. It is very similar to XML-RPC and in fact can be thought of as a port of XML-RPC.

Just like it’s sister protocol, it is widely supported. However it does shine in readability due to the fact that it encodes information in JSON (Javascript Object Notation) which is easily human readable and easy to parse for machines.

SOAP

SOAP (Simple Object Access Protocol) just like XML-RPC uses XML. SOAP enables a service to remotely trigger a function in a remote machine.

The protocol is web compliant and usually can be served through the normal port 80. However it can also be used with other protocols including SMTP, as such it can be used in a wider variety of environments and applications.

CORBA

CORBA(Common Object Request Broker Architecture) was developed by the Object Management Group. The system was designed to provide standard for interoperability of object based software components in a distributed environment.

Objects publish their interfaces using the Interface Definition Language (IDL) as defined in the CORBA specification.

This means that the protocol is not as web friendly and typically requires special ports open. Though it tends to be much faster than JSON-RPC or XML-RPC since it does not carry the burden of the verbosity that XML and JSON bring.

Pervasive Component System

PECOS (PErvasive COmponent System) is a component based model for embedded systems. It consists mainly of components communicating through ports. It provides an environment that supports the specification, composition, configuration checking, and deployment of embedded systems built from software components.

Depending on your situation, one of the above protocols might make the best business sense for your application. If however you can not make a business case for it or you are not sure what would work for you, stick to REST.

For more on the case against RPC based systems. See

A Critique of the Remote Procedure Call Paradigm

Have you ever used any of the above protocols in your own applications? Lets talk, comment below.

As usual don’t forget to Signup

Facebooktwittergoogle_plusredditpinterestlinkedinmail

CTags management in PHP

We have already talked about ctags before in the entry Text Editors and CTags

However if you are a PHP developer then you may have noticed that the tag command ctags -R . becomes awfully slow for anything but trivial projects.

This is usually as a result of the ctags file becoming too large from indexing entries from composer.

To take care of this problem, simply create two indexes, one for your src folder or whichever folder you use as sources folder and one for the vendor folder which contains all external libraries code.

You can achieve this separation by doing the following from the root of your php application

  1. rm tags \\If you already have a tags file
  2. ctags -R --PHP-kinds=+cf src \\Creates the tags file for your sources folder
  3. ctags -R --PHP-kinds=+cf -f tags.vendors vendor \\Creates tags file for your vendor directory

Now when you run ctags -R . only the files in your src directory will get reindexed.

This also implies that you manually need to reindex the vendor tags by running the command shown in 3 above. This only needs to happen when you update your composer file. Instructions on automating this part are in the Text Editors and CTags article.

If you enjoyed this, remember to signup for the weekly newsletter from the form on the right.

Thank you for reading.

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Using status codes and headers

HTTP enables communication between remote machines. Most developers only take care of the content part of the communication, that is the part that the user gets to see.

It is however equally important to engage intermediate machines in the conversation.

3 way communication

3 way communication

We do this by using HTTP status codes and headers.

A sample conversation for login would go something like this

#Request
GET     /protected/resource       HTTP/1.1        
Host:   www.example.org 
#Response
HTTP/1.1 401 Unauthorized
WWW-Authenticate:Basic realm="Protected Resources"    
Content-Type:application/json;charset=UTF-8
{
    "error":true,
    "message":"Unauthorized request"
}

In the above interaction we have informed the user that they are not allowed to make this request. But also we have told intermediary machines/services not to retry the request as well as provided the next steps.

If you we’re using a browser a basic auth login window would pop up on this response.

Do not go crazy with the realm value. It is meant to be opaque, that is your backend system can change without necessitating change of this value.

Next on the conversation, assuming the client has passed the server authentication challenge, is actually fetching the resource.

#Request
GET  /protected/resource HTTP/1.1
Host: www.example.org
Authorization:Basic cGhvdG9hcHAuMDAxOmJhc2ljYXV0aA==        
#Response
HTTP/1.1 200 OK
Vary:Authorization
Content-Type:application/json;charset-UTF8

{
    "error":false,
    "message":"This is my secret please keep it safe"
}

The server in this case confirmed the authorization header. Requests without it or with improper ones would have returned a 401 as we had seen earlier.

Now intermediary machines know that the request is authorized and can repeat the request say in case of network failure.

The Vary header informs the client machine on what other headers influence the request. So clients know to repeat this request an authorization header is required.

However by default GET requests are cached. This is ordinarily a good thing, the server is saved from the extra load of fulfilling requests and the client experiences less latency. In cases of protected resources this may not be ideal, we should consider limiting the amount of time the client and any intermediaries store the content.

This can be done by looping in the machines to the conversation once more as such

#Request
GET  /protected/resource HTTP/1.1
Host: www.example.org
Authorization:Basic cGhvdG9hcHAuMDAxOmJhc2ljYXV0aA==        
#Response
HTTP/1.1 200 OK
Cache-Control:max-age:3600,private
Vary:Authorization
Content-Type:application/json;charset-UTF8

{
    "error":false,
    "message":"This is my secret please keep it safe"
}

The cache control then ensures that this intermediaries do not store the data for more than a specified amount of time, in this case 3600 seconds or 1 hour. The private directive ensures that the cache is not shared or served to other clients.

If you liked this piece, sign up for our weekly newsletter.

Lets keep the conversation going.

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Common rel types

In a previous article, we talked about the rel attribute, http://blog.chenchatech.com/2015/05/the-rel-attribute/.

In this entry we have a sample list of common used link relations.

self

Use this type to link to the preferred URI of the resource.

alternate

Use this type when providing a link to a URI for an alternative version of the same resource.

edit

Use this type to link to a URI that clients can use to edit the resource.

Use this type to link to a related resource.

previous

Use these types to link to the previous or next resource in an ordered series of resources. and next

first and last

Use these types to link to the first and last resources in an ordered series of resources, e.g., to the first and last resources in a collection.

HTML Supported

  • alternate
  • stylesheet
  • start
  • next
  • prev
  • contents
  • index
  • glossary
  • copyright
  • chapter
  • section
  • subsection
  • appendix
  • bookmark

HTML 5 Specific

  • archives
  • feed
  • pingback

To see full list of link relations for public use see. https://tools.ietf.org/html/draft-nottingham-http-link-header-10

Facebooktwittergoogle_plusredditpinterestlinkedinmail

KISS

Despite the amorous title, this article is about an iron law for master engineers everywhere. It is an acronym that stands for:

Keep It Simple Stupid

A typical workflow for tackling a problem it involves breaking down the problem into small chunks that the developer can easily understand then build the solutions and integrate. This is called modular design.

The problem is we typically don’t get to an appropriate level of modularity. To define the appropriate level then we must consider the quote by renowned aeronautical engineer Antoine de Saint-Exupéry

Perfection is attained not when there is nothing more to add, but when there is nothing more to remove

So there we have it, our first advantage of applying the KISS principle in cracking a programming challenge.

There are many advantages including:

  • Understand-ability: Systems designed with the principle tend to be much easier to grok.
  • Team size: Because the systems are easier to understand, developers of varying skill sets and exposure can contribute to its development.
  • Flexibility: With clear understanding of the system, it becomes much more easier to modify its components.
  • Size: The architecture allows for much bigger applications.
  • speed: It is much quicker to design simple systems than complex ones.
  • Quality: Simple systems tend to have less bugs, and bugs that occur can be detected and fixed much more easily.

There are many more advantages to this principle, even over and above engineering software.

Have you applied this principle in any of your own projects? Comment below lets keep the conversation going.

Facebooktwittergoogle_plusredditpinterestlinkedinmail

The rel attribute

The rel attribute (relation type) is among one of the most misunderstood attributes in markup languages (xml, html, xhtml etc)

The simplest way to explain it is that it provides the semantics of the link. Thus answering the questions:

  • What resource does the URI refer to
  • What is the significance of the link
  • What kind of actions can a client perform on the resource at the URI?
  • What are the supported representation formats for requests and responses for that resource

Hope this has helped you understand the attribute a bit more.

Till next time, happy linking!

Facebooktwittergoogle_plusredditpinterestlinkedinmail

DRY up your API with microformats

Most API developers face the problem of multiple representation of the same resource. ie

  • HTML/XHTML for humans
  • JSON/XML for Servers
  • iCal for Calenders
  • etc

This is not only a technical challenge wasting developer hours but also a fertile ground for bugs. Wouldn’t it be nice if we could have representations that both humans and machines could understand?

You guessed it! microformats

According to their wiki, microformats can be described as.

Designed for humans first and machines second, microformats are a set of simple, open data formats built upon existing and widely adopted standards. Instead of throwing away what works today, microformats intend to solve simpler problems first by adapting to current behaviors and usage patterns.

Microformats work by embedding in existing html eg

<!--Example lifted from http://microformats.org/wiki/hcard-->
<div class="vcard">
 <a class="url fn" href="http://tantek.com/">Tantek Çelik</a>
</div>

Thus a parser would be able to pick out the details it needs and when rendered in a browser a user would just see it as normal clickable link.

I know by now you may not be feeling too eager to spend even more time learning a new technology but I think this one is definately worth it. And not just because microformats already power over 70% of standard web formats.

Benefits of htags

Engaging features

With microformats you get active features for free for example

  • hcard Enables your users to quickly save your details in their phonebooks
  • hCalender Your users can add your events to calendars.

Search results

SEO is very important to most if not all businesses with an online presence. Microformats can greatly assist you with this task as well.

  • hProduct Standard formats are easy on search engines and can enable comparison sites work for you.
  • hRecipe The market for recipes is bigger than most people think. In fact google has a search engine for recipes Google Recipe
  • hResume for seekers and employers
  • hReviews for re viewable products, services, businesses, events, etc
  • Check out more formats available at Microformats wiki

Developer productivity

Bill gates is famously quoted

I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.

I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.

Well microformats is the tool for the lazy developer.

  • It is easier to build
  • Minimize duplication of content
  • Far more user friendly than XML or even JSON for both developers and end users.
  • Provides facilities for extension such as rel-me rel-author rel-license

I hope I have whetted your appetite and you will take the time to master this awesome tool.

Till next time, happy coding!

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Text Editors and CTags

A while ago I talked about IDEs vs Text Editors why-you-should-learn-a-text-editor. This may have inspired you to try out vim.

If you are coming from an IDE background, then you must have noticed a key weakness in vim. That is that you can not immediately jump to function/class definitions. This can be quite a challenge for large projects. Cue in ctags

Tag Cloud

Tag Cloud

Ctags supports 40+ languages. You can almost be certain your language is supported.

To install ctags on a debian machine run.

sudo apt-get install exuberant-ctags

This should install the latest version of ctags.

Next you need to index your project so that vim and any other text editor for that matter, can consume it.

To do this navigate to the root of your folder and run ctags -R .

cd /var/www/{project_root}
ctags -R .

You could ofcos run the bash ctags -R command from any directory as long as you provided the correct path.

This is likely to take quite a while to complete. Luckily ctags is not a noisy utility and thus you can run

ctags -R . &

To push it to the background. This way you can continue working.

When the process is done you will have a shiny new folder called tags. Do not delete this folder, but consider adding it to your .gitignre file. See what_to_ignore

Now that your tags are ready you can use them in vim as follows

  1. Navigate your document such that the cursor is on top of the term which you would like to navigate to its position
  2. Press <c-]> If the definition exists this should jump you to the file
  3. You can jump back by pressing <c-i> once done reviewing the source document.

It is important to note that you need to continue updating your tags index whenever you add new classes/functions. The process is still the same really, how you do it thou is upto you.

  • For php developers, you can put the tags generator in your composer.json file in the post-update-cmd section
  • Put the command in your vim MakeFile so that update can be done when building the app
  • Use a plugin such as easy tags
  • Any script that best fits your workflow

Hope this eases your path to vim mastery.

Till next time, happy tagging!.

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Designing Collections

In every web project that you do at one point you will have to handle collections.

Collections are entities that are structurally or syntatically similar. Examples would include:

  • Users
  • Books
  • Apples

Collection of fruites

Collection of fruites

When designing collections it is very tempting to include all the attributes in the collection.

For example we may be tempted to provide something of this sort

{
  "products": {
    "link": {
      "-rel": "self",
      "-href": "http://www.example.org/catalog/products"
    },
    "automobile": {
      "id": "9001",
      "link": {
        "-rel": "self",
        "-href": "http://www.example.org/catalog/product/9001"
      },
      "make": "Smart",
      "model": "Fortwo Convertible",
      "year": "2009",
      "class": {
        "-classid": "small",
        "#text": "Small Car"
      },
      "mpg": {
        "city": "33",
        "highway": "41"
      },
      "drivetrain": "2WD",
      "list-price": {
        "-currency": "USD",
        "#text": "19495"
      }
    },
    "sailboat": {
      "id": "10101",
      "link": {
        "-rel": "self",
        "-href": "http://www.example.org/catalog/product/10101"
      },
      "make": "Jeanneau",
      "model": "Sunfast 3200",
      "year": "2008",
      "length": {
        "-unit": "ft",
        "#text": "32"
      },
      "hull-type": "fiberglass",
      "number-of-engines": "1",
      "list-price": {
        "-currency": "USD",
        "#text": "95995"
      }
    }
  }
}

In the above example, we included too much detail per item. Anyone trying to consume this particular resource is probably only interested in common properties of the collection.

{
  "products": {
    "link": {
      "-rel": "self",
      "-href": "http://www.example.org/catalog/products"
    },
    "product": [
      {
        "-type": "automobile",
        "id": "9001",
        "link": {
          "-rel": "self",
          "-href": "http://www.example.org/catalog/product/9001"
        },
        "make": "Smart",
        "model": "Fortwo Convertible",
        "year": "2009",
        "list-price": {
          "-currency": "USD",
          "#text": "19495"
        }
      },
      {
        "-type": "sailboat",
        "id": "10101",
        "link": {
          "-rel": "self",
          "-href": "http://www.example.org/catalog/product/10101"
        },
        "make": "Jeanneau",
        "model": "Sunfast   3200",
        "year": "2008",
        "list-price": {
          "-currency": "USD",
          "#text": "95995"
        }
      }
    ]
  }
}

In this example we have removed the extranous fields and a consumer of the collection can as such treat them as one.

In general to summarize a collection look for salient properties across the items in the collection.

Finally it is important to always include meta data of the collection. This includes the fields:

  • total size
  • size per page
  • current page
  • self link
  • prev
  • next

By including this data we give the quality of affordance, that is the resource describes itself and thus can be easily used by diverse clients.

Till next time, happy designing!

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Restarting Apigility

Apigility is a great tool for designing API’s

https://apigility.org/

However I see no easy way to restart the server. Or at least they are not documenting it.

Anyways to do it. First navigate to the installation folder the run

php -S 0.0.0.0:8888 -t public public/index.php
Corrections

The reason Apigility don’t provide instructions to start the server like this is because this starts out php test server.

You can launch the application anytime by serving out the application via your usual web server (nginx, apache, wamp etc).

Thank you Matthew for the correction.

Facebooktwittergoogle_plusredditpinterestlinkedinmail