Architecture pattern, Architectural style and Design pattern

In the software world we have three terminologies which might confuse us they are: Architecture pattern, Architectural style and Design pattern. Following we have detailed the differences between the three:


Architecture pattern: An Architectural Pattern is a way of solving a recurring architectural problem. MVC, for instance, solves the problem of separating the UI from the model. Sensor-Controller-Actuator is a pattern that will help you with the problem of actuating in face of several input senses.

Architectural Style: An Architectural Style, on the other hand, is just a name given to a recurrent Architectural Design. Contrary to a Pattern, it doesn’t exist to “solve” a problem. Client/server, Main program & subroutine and Abstract Data Types / OO, Service Oriented Architecture (SOA), REST does not solve a problem. They are just concepts or names given. Also, a single architecture can contain several architectural styles, and each architectural style can make use of several architectural patterns.

Design Pattern: A design pattern is a solution at code level; it talks about classes, functions and logic of how the code flows.



Read more:

What is REST? Concepts in RESTful API Design

What is REST?



REST stands for Representational State Transfer. (It is sometimes spelled “ReST”.) It relies on a stateless, client-server, cacheable communications protocol — and in virtually all cases, the HTTP protocol is used.

REST is an architecture style for designing networked applications. The idea is that, rather than using complex mechanisms such as CORBA, RPC or SOAP to connect between machines, simple HTTP is used to make calls between machines.

In many ways, the World Wide Web itself, based on HTTP, can be viewed as a REST-based architecture.

REST uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.

One thing that is not part of a good REST design is cookies: The “ST” in “REST” stands for “State Transfer”, and indeed, in a good REST design operations are self-contained, and each request carries with it (transfers) all the information (state) that the server needs in order to complete it.

It’s easy to see why Web Services are often used with libraries that create the SOAP/HTTP request and send it over, and then parse the SOAP response. With REST, a simple network connection is all you need. You can even test the API directly, using your browser.

A nice analogy for REST vs. SOAP is mailing a letter: with SOAP, you’re using an envelope; with REST, it’s a postcard.

One option is not acceptable as a REST response format, except in very specific cases: HTML, or any other format which is meant for human consumption and is not easily processed by clients. The specific exception is, of course, when the REST service is documented to return a human-readable document; and when viewing the entire WWW as a RESTful application, we find that HTML is in fact the most common REST response format

Resources are the key element of a true RESTful design, as opposed to “methods” or “services” used in RPC and SOAP Web Services, respectively. You do not issue a “getProductName” and then a “getProductPrice” RPC calls in REST; rather, you view the product data as a resource — and this resource should contain all the required information (or links to it).

Rather than letting clients construct URLs for additional actions, include the actual URLs with REST responses.

ROA (REST Oriented Architecture) is just a fancy name for a SOA (Service Based Architecture) using REST services.

With version 2.0, WSDL supports all HTTP verbs and it is now considered to be an acceptable method of documenting REST services. The second alternative is WADL, the Web Application Description Language

Read More:




REST is neither a framework nor a technology. “REST is an Architectural Style built on certain principles using the current HTTP web fundamentals”.

Architectural style

A constraint is a rule that induces one or more software architecture properties. A group of constraints is called a style. The REST style is a group of six major constraints that induce the various properties needed for the Web. In order for architecture to be viewed as REST architecture, it must satisfy all of these constraints. They are:

  1. Client/server
  2. Stateless communication
  3. Caching
  4. Uniform Interface
  5. Layered System
  6. Code On demand


Requests and responses are built around the transfer of representations of resources. A resource can essentially be any coherent and meaningful concept that may be addressed. A representation of a resource is typically a document that captures the current or intended state of a resource.

The client begins sending requests when it is ready to make the transition to a new state. While one or more requests are outstanding, the client is considered to be in transition. The representation of each application state contains links that may be used the next time the client chooses to initiate a new state-transition.

Representational State Transfer is intended to evoke an image of how a well-designed Web application behaves: presented with a network of Web pages (a virtual state-machine), the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use.[10]

REST was initially described in the context of HTTP, but it is not limited to that protocol.



REST uses HTTP operations and other existing features of the HTTP protocol. For example, layered proxy and gateway components perform additional functions on the network, such as HTTP caching and security enforcement.

SOAP RPC over HTTP, on the other hand, encourages each application designer to define new, application-specific operations that supplant HTTP operations. An example could be: getUsers(), savePurchaseOrder(string CustomerID, string PurchaseOrderID)

This additive, “re-invention of the wheel” vocabulary — defined on the spot and subject to individual judgment or preference — disregards many of HTTP’s existing capabilities, such as authentication, caching, and content-type negotiation.[12] The advantage of SOAP over REST comes from this same limitation: since it does not take advantage of HTTP conventions, SOAP works equally well over raw TCP, named pipes, message queues, etc.

Central principle

An important concept in REST is the existence of resources (sources of specific information), each of which is referenced with a global identifier (e.g., a URI* in HTTP). In order to manipulate these resources, components of the network (user agents and origin servers) communicate via a standardized interface (e.g., HTTP) and exchange representations of these resources (the actual documents conveying the information). For example, a resource that represents a circle (as a logical object) may accept and return a representation that specifies a center point and radius, formatted in SVG, but may also accept and return a representation that specifies any three distinct points along the curve (since this also uniquely identifies a circle) as a comma-separated list.

Any number of connectors (e.g., clientsserverscachestunnels, etc.) can mediate the request, but each does so without “seeing past” its own request (referred to as “layering”, another constraint of REST and a common principle in many other parts of information and networking architecture). Thus, an application can interact with a resource by knowing two things: the identifier of the resource and the action required—it does not need to know whether there are caches, proxies, gateways, firewalls, tunnels, or anything else between it and the server actually holding the information. The application does, however, need to understand the format of the information (representation) returned, which is typically an HTMLXML, or JSON document of some kind, although it may be an image, plain text, or any other content.


* A URL is a URI that, in addition to identifying a web resource, specifies the means of acting upon or obtaining the representation: providing both the primary access mechanism, and the network “location”. For example, the URL refers to a resource identified as /wiki/Main_Page whose representation, in the form of HTML and related code, is obtainable via HyperText Transfer Protocol (http://) from a network host whose domain name is

URN is a URI that identifies a resource by name, in a particular namespace.

RESTful web APIs

A RESTful web API (also called a RESTful web service) is a web API implemented using HTTP and REST principles. It is a collection of resources, with four defined aspects:

  • the base URI for the web API, such as
  • the Internet media type of the data supported by the web API. This is often JSON but can be any other valid Internet media type provided that it is a valid hypertext standard.
  • the set of operations supported by the web API using HTTP methods (e.g., GET, PUT, POST, or DELETE).
  • The API must be hypertext driven.[14]


HyperMedia System

Hypermedia is used as a logical extension of the term hypertext in which graphics, audio, video, plain text and hyperlinks intertwine to create a generally non-linear medium of information. This contrasts with the broader term multimedia, which may be used to describe non-interactive linear presentations as well as hypermedia. It is also related to the field of electronic literature.

The World Wide Web is a classic example of hypermedia, whereas a non-interactive cinema presentation is an example of standard multimedia due to the absence of hyperlinks.

Multimedia development software such as Adobe FlashAdobe DirectorMacromedia Authorware, and MatchWare Mediator may be used to create stand-alone hypermedia applications, with emphasis on entertainment content.

A distributed hypermedia system provides a group of users logically transparent access to heterogeneous hypermedia information repositories that are distributed across local- and wide-area networks

REST Architectural Elements


Life is a distributed object system. However, communication among humans is a distributed hypermedia system, where the mind’s intellect, voice+gestures, eyes+ears, and imagination are all components.

The Representational State Transfer (REST) style is an abstraction of the architectural elements within a distributed hypermedia system(eg. WWW).

REST ignores the details of component implementation and protocol syntax in order to focus on the roles of components, the constraints upon their interaction with other components, and their interpretation of significant data elements. It encompasses the fundamental constraints upon components, connectors, and data that define the basis of the Web architecture, and thus the essence of its behavior as a network-based application.

Architectural elements

  1. 1.       Connectors represent the activities involved in accessing resources and transferring representations
  2. 2.       Components the various software that interacts with one another are called components
  3. Data Elements components communicate by transferring representations of the current or desired state of data elements. REST identifies six data elements: a resource, resource identifier, resource metadata, representation, representation metadata, and control data, shown in the table below:


Moving On

Mashup services (ppt) can be built on top of RESTful APIs. Eg. Yahoo Pipes, Denodo, or JackBe/Presto.

REST principles such as simplicity, scalability, performance, reliability, visibility and evolvability will enable the framework interface to support human, mobile, mashup, and programmatic clients.

But REST has its issues: HTTP does not provide built-in quality of service (QoS) features such as reliability, security, transactional integrity, pub-sub, and event delivery.

We can have both method-oriented and resource-oriented interfaces by using a façade.

Security in RESTful Web services is limited. Encryption and digital signatures are handled by layering HTTP over TLS. Authentication is typically handled by supplying HTTP basic or digest credentials in the WWW-Authenticate header.

Implementing transport security using SSL impacts REST’s self-descriptiveness constraint. Public RESTful APIs such as Amazon and have invented their own solutions, usually incorporating access keys. Popular authentication solutions include self-provisioned developer keys, session-based authentication, WS- security, Open identity schemes like OpenID and OAuth or shared secrets used by AWS.

Check out Twillo, Twitter’s HTTP Push, and Granularity, Authentication and Exception handling. Explore Swagger, Mashape or Apiary.

Think this way about system design: Let go object orientation and RPC for resource orientation and hypermedia.

Intel’s Mashery [specially I/O docs], Apigee [used by MorningStar] make it easy to explore, test and debug APIs, 3scale with oAuth support or Layer7. Cloud API management services offer sophisticated caching mechanisms that improve application performance for dispersed users of Web, social and mobile applications.

Cloud Service Broker choices: Liaison, Appirio, Cloud Sherpas, StrikeIron, Kony.

Self Notes:

Resource: The address (URI)

Representation of a resource : The data that the resource serves

Web API Best Practices

Heavily influenced by the apigee talk.

Web Api Deisgn paper and also from the Google API Craft forum group.

1.      Keep verbs out of the URLs.

a.       Instead of /getAccounts?account=101-22234 use /Accounts/101-22234 with the GET HTTP REST method







Create new Account

Return all Accounts

Update all Accounts

Delete all Accounts



returns 123 Account

If 123 exists then update it, else error

Delete 123


a.      How do I get all accounts for a client?  This requires associations
between Clients and Accounts.  E.g. Show me all accounts for a Client
(Joe): GET /Clients/123/Accounts

b.     (/resource/identifier/resource)

Use ‘?’ for optional parameters

a.     GET /Accounts?type=a&date_range=current_month


a.     Errors can be communicated via HTTP codes and also via contents of the
message that is returned.  The best practice would be to use a very small
set of HTTP error codes.

i.      Eg. HTTP Status Code: 401

{“type”: “error”,
“component”: “AuthManager”, “message”:
“Authentication required”}


a.     Versioning is a good way to maintain compatibility of services with
older clients and at the same time add new features for newer clients. The best
practice is not to ever introduce a incompatible
change in your service.  If you have to make a change that is not
compatible with older clients, make sure that it is done in a way that it does
not impact existing clients.

b.     Eg.

GET /v2/Clients/121
HTTP/1.1 or GET /Clients/121?v=2 HTTP/1.1:

GET /v1/Clients/121
HTTP/1.1 or GET /Clients/121?v=1 HTTP/1.1:

c.     OR Version in Media-type:
In this option the caller requests a specific version as a part of the media

GET /Clients/121


The version in URL
options is recommended, specifically the one that is passed in the query

6.      Partial Responses

There are times that the application does not need
all the data that is returned by the service.  It is useful for the caller
to only get the data they need.  To achieve this, the caller can request
the specific fields or JSON objects they need.

Eg. GET /Clients/121?v=1,fields=first-name,street,city

GET /Clients/121?v=2,objects=”address”,limit=10,offset=0

If omitted default is =limit=10,offiset=0

Both these methods allow for managing the amount of
data sent to the callers.

pragmatic use of Hypermedia based
API design
.   Hypermedia is one othe
main constraints of REST and often ignored in RESTful
API design.  There are two standards for designing hypermedia based api design aka HATEOAS

1.      HAL (Hypertext
Application Language) BEST

2.      Collection+JSON

 Some example of this is practice is the BESTPaypal REST API. (One of the key features of the PayPal REST API is HATEOAS

(Hypertext As The Engine Of Application State). At its core, HATEAOAS provides a way to interact with the REST Payment API entirely through hyperlinks. With each call that you make to the API, we’ll return an array of links that allow you to request more information about a call and to further interact with the API. You no longer need to hard code the logic necessary to use the PayPal REST API. HATEOAS links are contextual, so you only get the information that is relative to a specific request.)

HATEOAS, an abbreviation for Hypermedia as the Engine of Application State, is a constraint of the REST application architecture that distinguishes it from most other network application architectures. The principle is that a client interacts with a network application entirely throughhypermedia provided dynamically by application servers. A REST client needs no prior knowledge about how to interact with any particular application or server beyond a generic understanding of hypermedia.

In a service-oriented architecture (SOA), clients and servers interact through a fixedinterface shared through documentation or an interface description language (IDL).

RESTful service can be described as well to be available for the client code-generation, RSDL (RESTful Service Description Language) using dynamic metadata collection to achieve this goal.

The HATEOAS constraint serves to decouple client and server in a way that allows the server to evolve functionality independently.

 A REST client enters a REST application through a simple fixed URLAll future actions the client may take are discovered within resource representations returned from the

server. The media types used for these representations, and the link relations they may contain, are standardized. The client transitions through application states by selecting from the links
within a representation or by manipulating the representation in other ways afforded by its media type. In this way, RESTful interaction is driven by hypermedia, rather than out-of-band information.

A client does not need to understand every media type and communication mechanism offered by the server and this understanding may be improved on the fly through “code-on-demand” provided to the client by the server.



1.      OST /Accounts/101

2.     // Non – HATEOAS response  

3.     [  

4.          { “type”: “success”, “component”: “CreateAccount”, “message”: “Account Created successfully”}  

5.    ]  

6.    // HATEOAS response  

8.    [  

9.    { “type”: “success”, “component”: “CreateAccount”, “message”: “Account Created successfully”},  

10.   “_links”: {  

11.  12.            {  

13.             “href“: “http://&#8230;./Accounts/101”  

14.               “rel“: “self”  

15.               “method”: “GET”  

16.            },  

17.               “href“: “http://&#8230;./Accounts/101”  

18.               “rel“: “close”  

19.               “method”: “DELETE”  

20.            },  

21.            {    

22.               “href“: “http://&#8230;./Accounts/101?action=approve”  

23.               “rel“: “approve”  

24.               “method”: “PUT”  

25.            }  

26.          }  

27.     ]  

 Advantages of HATEOAS

1.       Reduced client coding errors: Most of the clients have to construct URI’s to call the next method on the API.  If the API server is the one that does the URI construction, the chance of errors is very low.

2.       Reduced Invalid state transitions: When the client decides which URI to call and when, they run the risk of attempting to request state transitions that are not valid for the current state of the server side resource.  The server knows the appropriate state transitions and returns them to the client, reducing the possibility of errors.

3.       API evolution without major impactIf the server decides that the URI format it was using was not correct and changes it, the client does not need to update its code.  Since the server returns the URI and the client users it directly, changes in the URI format can be made by the server.


1.       No Standards: There is no standard way to represent the links published by API.  We could come up with our own standards, but it will probably change when there is one.  The current draft of the Hypertext Application Standard is addressing this but is not final yet.

2.       Full featured applications cannot display state transitions directly returned form the API server.  They might need to perform business and validation logic to display more that what is returned from the API server.

Only use HATEOAS for simple applications that require minimal state in the application and can infer all state transitions from the server to display them on the UI.

Do not makeall APIs HATEOAS compliant, use judiciously only where you see a benefit. 

Follow the HAL standard.

What to do for ERRORS?

 If the application runs into an error while servicing the request (e.g. cannot connect to the database), then there are two options listed below.

Which one do you think is a better approach?

 Option 1 (Facebook style – unfortunately cannot post the link as we are blocked from facebook) where the response is 200 and details are in the body, which is the error

HTTP Status Code: 200

{“type”: “error”, “component”: “AccountService”,
“message”: “Cannot call stored prod SQLError=2013”}

or option 2 (Google Docs API style) use 400 or 500 error in HTTP and provide the details in the response.

HTTP Status Code:500

{“type”: “error”, “component”: “AccountService”,
“message”: “Cannot call stored prod SQLError=2013”}

èshould stick to the official RFC2616 definitions of the HTTP response codes. The difference is that a 400 error should indicate a bad request (malformed) therefore no point in retrying the same request, whereas a 500 error is an Internal Server Error and the client may want to retry later (with some reasonable exponential back-off strategy).

In the case of Account Not Found, I actually think the response should be a 200 (you were right previously), because at the HTTP level the request succeeded, except no use
data is found to match the request. This is different than a 404 where the actual HTTP end-point is not found.

èLeave the HTTP error code to the hosting web server.  The app does not return specific HTTP errors.  If the request message reaches that REST endpoint (the app) then

the app should always return success (that will be translated to a 200 by the hosting web server if using C# .net) even if there is some internal error (e.g. cannot reach database or user input validation).  The error details are sent back as a response.

if(http_code == 200) {

     if(body.type ==
“success”) {

//success: parse message and take appropriate action

     else {

//application specific failure

return(“Application error”, body.component, body.message);

} else {

     //HTTP failure

     return(“HTTP error”, http_code)


REST API error return good practices




REST+JSON API Design – Best Practices for Developers

REST+JSON API Design – Best Practices for Developers

REST = Dist. Hypermedia (docs can link to other docs) + Media Type (specification of data format and data parsing rules by consumer i.e. Representation of the Resource)


1.      HATEOAS: Hypermedia As The Engine Of Aplication State

2.      Resources: Accounts, Clients


Don’t create URLs based on Behavior Eg. /getAccount, /getAllAccounts
etc. as it will Explode rapidly. This is like Soap RPC

2.      See Resoueces as:

a.     Collection of Instances (/application)

b.      Single Instance (/applications/InstanceID)

BEHAVIOR: use HTTP verbs: get, put, post, delete to correlate with CRUD

PUT is supposed to be IDEMPOTENT, ie however many times its called it should result in same server state. So make sure when its used to

Create or Update record, all the fields of the record are passed. Don’t support Partial Updates. Use PATCH or POST for that.


Used to create record. So used at Collection level Eg. PUT /applications


“name” : “sdf”


Response has to be 201 if created and not 200

Location:    ie the URL of created resource Should be returned

For partial update use post and return 200 and no need for location….


Most imp. Both these should ALWAYS be set:

1.     Configured by Accept Header in REQUEST

2.     Configured by Content-Type Header in RESPONSE

If in req. I say : app/json, text/plain means that I support both but prefer json

Can create ur own Data Types eg. App/foo+json with its own Parsing Rules (provided the clients know those)


Make is short: http(s)://


Best to put it in:

1.      media type Accept Header: ap/json;v=1

2.      http(s)://      …this is easiest
for u and clients both

This is DATA interchange so keep versions as whole nos. not

Use camelCase: myArray.forEach, account.myName

Use ISO 8601 specs..use UTC (consistent for clients and
DB as well)

Every RESOURCE should have its URL and it should be
returned whenever the resource is sent to client at top level:


“Href”” https://dfsdf/dsfdf/123




Xml has xlink JSON doesn’t

Idea is that i’m returning a resource but that res. Has
links to other do I represent that link….

So in case u have to return a Account :


“href”: “URL of Account”,

“Name” : “tarun”,


Now if u wanna link it to Directory, which is another INSTANCE/COLLECTION, not a prop in Account, then do


“href”: “dfdf”,

“Name” : “tarun”,

“directory”: {      // INSTANCE

“href”: “URL of Directory”


“directories”: {  // COLLECTION

“href”: “URL of Directories”



Note that here the Client asks only for Account resource: GET accounts/123


Idea is that i’m returning a resource but that res. Has links to other do I represent those other RESOURCES fully (by embedding them in the original requested resource)….




“href”: “dfdf”,

“Name” : “tarun”,

“directory”: {      // INSTANCE

“href”: “URL of Directory”,

“name”: “myDir”,



Note that wrt caching , the URL with Query parameter is considered as a separate resource than that without Q pars.


GET /accounts/123?fileds=name,sdf,directory(name)


?offset=<start here>&limit=<gimme these many records>

THEN BEST Is for server to reply like this:

200 OK


“href”: “fdfsd/groups”,

“offest”: 0,

“limit”: 25,

“first”: {“href”: “../accounts/1/groups?offset=0”}.

“previous”: null,  // as this the the 1st

“last”: {“href”: “../accounts/1/groups?offset=124”}.

“items”: {


“href”: “”



“href”: “”





Each Account can be in Many Groups


Each Group can have many Accounts


Represent each Reference as a RESOURCE


Eg. Account A belongs
to Group P and Q

Group p contains
Account A and B

Then there are the
following groupMembership resources:

<![if !supportLists]>1.
<![endif]>gm1 : Account A, Group P

<![if !supportLists]>2.
<![endif]>gm2 : Account A, Group Q

<![if !supportLists]>3.
<![endif]>gm1 : Account B, Group P

And the resource will be like this:

GET /groupMemberships/1


Href: /groupMemberships/1,

Timestamp: //when this relationship
was created etc. parameters can be added

“account”: {



Group: {




Eg. Account bject representing its group memberships is :


Href: ../accounts/123,

Name : taryn,

Groups: {

Href: ‘../accounts/123/groups’


groupMemberships: {

href: ../ groupMemberships?accountId = 123




Don’t forsee the USER requirements. EXPOSE EVERYTHING


Eg. If the dir exists and the user is doing POST to create



Status: 409,

Code: 40924,

Property:name // what prop in dir failed

Message “directory named this already exists”


moreInfo: //GIVE URL For this




don’t maintain sessions

sessionID is not secure

Do not auth using URL as they can change..auth on the
underlying resource

Use existing protocols: OAuth1 better than 2

Don’t write custom auth scheme

Use API key and not password

<![endif]>401 Unauth ACTUALLY means NOT AUTHENTICATED means “u
need valid credentials for me to respond to this request”

403 “Forbidden”is AUTH ERROR means “I got ur
credentials and ur not allowed to access this resource”

Using HTTP Auth
, the server actually responds with challenge and not 401:

WWW_Auth: <scheme

Realm= “App name”

Then client sends another req. with
the Authorization: <scheme name> <data> Header //this is for
AUTHENTICATION but the header name is confusing

10.  API Keys

a.     Always use
this over username psswd

Random Key It is longer in length than psswd

Pssed issues not present

Speed (hash algos like bcrypt based on blowfish algo are faster, used in psswd, but API Key encrypt is diff…

Key is downloaded immediately and put in OS so harder to break, whereas pssws shared in email etc.


Server (init response with the Body ie Data): ETag:”123”

Client (later req): If-None-Match:”123”

Server (later response):

304 Not Modified

This way in the later req, the data is not sent again as the server knows that this ETag is the latest



send HTTP redirect to the client


abstraction layer so client talks to the same endpint forever and then the
layer redirects to the new path

well def. Media Types only


Stormpath FREE for Identity Mngmt and Access Control