Showing posts with label REST. Show all posts
Showing posts with label REST. Show all posts

Monday, 8 May 2017

REST Web Service API Guidelines

When building web services, one of the primary benefits of using REST over SOAP is the intuitive nature of service interfaces.  However, this simplicity of interface can very easily be eroded.  Below are some suggested (and hence flame proof) guidelines that could be followed to ensure continued interface simplicity:

Resource-Oriented
  • REST is resource-oriented, not service-oriented.  Resources are nouns, not verbs.

Addressable
  • Every resource must be addressable by means of at least one URI (name).  Names must be meaningful.
  • Clients cannot access resources directly - they deal in representations of that resource (e.g, XML, JSON, ...)  
  • Resource representations would ideally be addressable (so that they can be passed around as URIs, eg. /rest/bookmarks.xml)  The use of HTTP accept headers to specify representation is however acceptable, but should be provided as well as the addressable URI.

Share:

Wednesday, 14 January 2015

What is SOA?

What is SOA?  SOA or Service-Oriented Architecture is a software architecture pattern in which applications or systems are constructed from underlying (and usually distributed) software services that conform to a specific set of characteristics, namely:

1.Contract based
2. Location transparency
3. Autonomous
4. Abstract
5. Reusable
6. Composable
7. Stateless
8. Discoverable
9. Extensible
10. Loosely coupled

The primary goal of SOA is software development agility, i.e. the ability to respond the change easily, and cheaply, thus allowing businesses to rapidly respond to changing markets.

Services are typically (but by no means exclusively) implemented as web services, i.e. they operate over the ubiquitous web HTTP protocol, and are implemented either using XML-based SOAP or the lightweight (and more popular) REST paradigm.

The highly distributed nature of this architecture has resulted in a need for a runtime platform (the Enterprise Service Bus, ESB) to help manage the operation of these services, but also to handle complex enterprise integration scenarios involving multiple (and often legacy) platforms, protocols and security models - products like Oracle Service Bus or the open source Mule ESB.

In addition to being an integration solution, the service-oriented pattern also offers an opportunity for easier implementation of high-level business processes using Business Process Management (BPM) solutions that are often offered as part of the ESB product suite.

Service-oriented architecture is highly relevant to the rapidly growing cloud computing model where applications are built in the cloud as orchestrations over public cloud-based APIs, and we are seeing ESB vendors like WSO2 and MuleSoft in or moving into this space, offering cloud-based versions of their products, as well as API management products.

Some will argue that SOA is not new, and that distributed programming involving services has existed for a long time, and they are right.  However those early efforts stumbled on the hurdles of platform incompatibility and standards complexity.  Now, with ubiquitous, and easy to use protocols like REST, web service API development is growing rapidly, and the integration possibilities seem endless.

(What is SOA, Service Oriented Architecture)

Share:

REST Web Service Paradigm Shift

Moving your Service-Oriented Architecture (SOA) from RPC style (web) services to SOAP document-oriented services, or REST resource-oriented services requires a difficult mental paradigm shift.  The same kind of shift that was required for monolothic and procedural programmers to move to object-oriented programming styles.  This change is not easy, and not all will pass muster.  Failing to make the change will mean the difference between Just a Bunch of Web Services (JABOWS) or a fully-fledged SOA.

Ensuring that this mind shift does happen will require good organisation and strong, well-articulated guidance and governance.  Until the new pattern becomes habit, people will very quickly slip into old habits. 

Below are some guidelines and implementation suggestions from this blog:

Share:

Thursday, 10 July 2014

Excel REST Trading API Example

As much as I have a love-hate relationship with Microsoft, I have to admit the Excel has won me over as a power-user tool, particularly in the world of finance, where it may be used to access powerful back-end analytics servers to provide real-time yield curves and such like.

REST APIs such as IG's Web Trading API make this even easier, as this Excel VBA code snippet to get a list of open positions will hopefully demonstrate.  The sample assumes that a login /session request has already been executed and the client and account session tokens have been obtained.  The API key is the unique authorisation token required to access the API.

Public Function positions() As Collection

    ' Set up the HTTP access framework
    Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.6.0")
    ' Set the API URL
    Call oXMLHTTP.Open("GET", IG_API_HOST + "/positions", False)
    ' Set the HTTP request headers:
    ' Set the account session token
    Call oXMLHTTP.SetRequestHeader("X-SECURITY-TOKEN", m_accountToken)
    ' Set the client session token
    Call oXMLHTTP.SetRequestHeader("CST", m_clientToken)
    ' Set the API key
    Call oXMLHTTP.SetRequestHeader("X-IG-API-KEY", m_apiKey)
    ' Set the content type to JSON
    Call oXMLHTTP.SetRequestHeader("Content-Type", "application/json; chartset=utf-8")
    ' Set the requested response type to JSON
    Call oXMLHTTP.SetRequestHeader("Accept", "application/json; chartset=utf-8")
    ' Execute the request
    Call oXMLHTTP.send
    
    If oXMLHTTP.Status = 200 Then 
        ' Successful. A list of zero or more positions will have been returned
        ' Extract the response as a JSON object
        Dim data As Dictionary
        Set data = JSON.parse(oXMLHTTP.responseText)
        ' Get the list of positions from the response object
        Dim positions as Collection
        Set positions = data.Item("positions")
        ' If positions exist, iterate over the list         If Not positions Is Nothing Then
            Dim aPosition As Object
            ' Do something with the position, e.g. extract the instrument name of the underlying market
            For Each aPosition In positions
                  Dim instrumentName as String
                  Set instrumentName = aPosition.Item("market").Item("instrumentName")
                  ' etc
            Next
    Else 
        ' An error occurred
        MsgBox oXMLHTTP.responseText
        Set positions = Nothing
    End If
        
End Function
Share:

Monday, 30 June 2014

IG REST Trading API

Hot off the press is the news that IG (my esteemed employer) has launched its REST Trading API

The API provides REST-based and streaming access to a range of popular asset classes (including indices, forex, commodities, binaries and options), and includes functionality to:
  • Trade using risk management tools such as stops and limits
  • View real-time and historical market prices
  • Analyse market instrument and client sentiment information
  • Review account balances and trade history


IG already offers a well-established FIX API for corporate clients, but now with its new REST Trading API, IG's technology platform becomes much more easily and widely accessible, allowing for example:

  • Corporate partner integration without the start-up costs and complexity of FIX 
  • Trading strategy automation
  • Retail trading app development


The REST Trading API labs site offers getting started guides, API documentation, a downloadable sample trading app, and an interactive API companion app for trying out the REST APIs.  



The API will only be available in the UK initially, but the wider roll-out is imminent, so be sure to follow the labs site on Facebook or Twitter for updates.  

Related:

·         ForexMagnates: IG Opens API to Public Development, Launches IG Labs
·         FOW.com: IG rolls out new tech offering for traders


Share:

Tuesday, 19 February 2013

Thursday, 20 December 2012

REST Web Service Spring Error Handling

The Spring framework provides excellent support for building REST web services in a service-oriented architecture (SOA), as I have demonstrated in a previous post, but what is not immediately obvious is how best to deal with errors. Instead of throwing raw exceptions to the client, one would prefer to return a well-formed response consisting of an appropriate HTTP status code and a meaningul response body containing a structured error message in the response form (JSON, XML, ...) requested by the client.

For example, assuming you have a basic REST endpoint such as:

 @RequestMapping(value = "/samples", method = {RequestMethod.GET})
 @ResponseBody
 public SampleList findAllSamples() throws SampleException {
  return new SampleList(service.findAllSamples());
 }

It is good practice in general to not let implementation exceptions leave the service tier, so you might use aspects to catch these and rethrow them as service exceptions.  The code below catches a ReferenceNotFoundException from the data access tier and throws a service exception with the reference number and setting the desired http status code.  Another good practice is to avoid sending free text error messages to a service client, and instead to send structured messages that can be dealt with or rendered as the client sees fit.

@Aspect
@Component("exceptionHandler")
public class ExceptionHandler {

   /**
    * Exception handler for ReferenceNotFoundExceptions
    * 
    * @param nfe the exception being handled
    */
   @AfterThrowing(pointcut = "execution (* com.sample.service.*.*(..))", 
                                              throwing = "nfe")
   public void handleNotFoundException(ReferenceNotFoundException nfe) {
      throw new SampleException(
         new ReferenceNotFoundError(nfe.getReference()), 
                               HttpStatus.NOT_FOUND);
   }


Now to map the service exception (SampleException) to a meaningful HTTP response using the Spring 3 @ExceptionHandler annotation:

   @ExceptionHandler(SampleException.class)
   @ResponseBody
   public SampleErrorList exceptionHandler(SampleException se,
                 HttpServletRequest req,
                 HttpServletResponse res) throws IOException {

      res.setStatus(se.getHttpStatus());

      return new SampleErrorList(se.getErrors());

   }
 

It is also possible to set the HTTP status code using an annotation, but in this example the exception determines this, so the handler sets it programmatically.

See here for a downloadable working sample.

REST Web Service Spring Error Handling
Share:

Monday, 29 October 2012

SOAP vs REST web services


Comparing SOAP to REST for building web services is a bit like comparing apples with pears: SOAP is a protocol, REST is a pattern, and you could, if you felt so inclined, write RESTful services using SOAP.  However, when people ask this question, they usually mean: SOAP (as in WSDL, perhaps RPC style, WS-* standards), as opposed to REST (as in JSON/XML over HTTP)

Assuming you mean this, below are some pros and cons for each, but note this: REST is increasingly becoming the de-facto standard across the web, being used by the big public API providers in preference to SOAP. I reckon it's just a matter of time before this question will just go away.

Share:

Thursday, 25 October 2012

SOA - Governance Principles


Definition:-
Governance is the application of controls to processes that change corporate assets, with a view to ensuring that those assets comply with (or move towards compliance with) with a set of corporate goals
Governance Needs Balance:-
Given the necessary overheads of governance, a balance needs to be struck between too much governance (which will cripple processes), and too little governance (which will result in chaos).
Governance Needs A Raison D’être:-
Governance only makes sense against a backdrop of well-defined drivers and goals. For example, an organisation may decide to standardise on a particular architecture, or tool set, for reasons of reduced total cost of ownership. Governance would be used to drive or direct changes to current assets in compliance with these goals.
Governance Must Be Effective:-
Effective governance will impose light-weight, thorough and widely-accepted controls around the changes being applied to those assets. Governance that is seen as pointless, or a hindrance to progress, will be resisted and ineffective.
Share:

Wednesday, 17 October 2012

Building a REST Java web service API using the Spring framework

Building a REST-ful Java web service API has never been more restful than now, using version 3+ of the Spring framework.

 First some annotated Java code:

@Component
@Controller()
public class SampleController {

     @Autowired
     private SampleService service;

     @RequestMapping(value = "/samples/{reference}", method = {RequestMethod.GET})
     @ResponseBody
     public Sample getSampleByReference(@PathVariable String reference) {
          return service.getSampleByReference(reference);
      }
 }

Share:

Friday, 12 October 2012

Key considerations for securing your REST web service API


Securing your REST service API layer is not just about considering whether you should use OAuth 2.0 or not, or whether REST needs something like WS-Security.  It is about considering why you should care about security, who you are protecting your service against, what the risks are, and more general security principles than just authentication and authorisation.

Why?

Do your service API need securing?  The answer to this will depend on your business, and the nature of the service, but you will want to consider whether there are any reputational, financial or regulatory consequences to a security breach of your service, and if so, how to deal with it appropriately.

Share:

Thursday, 11 October 2012

Java as a Service - Monitoring the Java Web Service API

One key aspect of managing your public REST web service API is understanding your client usage.

There are several options for doing this, including configuring your IP sprayer to do quota management, or facading your services with a 3rd party service management product like Layer 7 or SOA Software, but you might also consider the very simple Java web service based solution using the open source JAMon library.

The sample code below illustrates a simple per-IP address monitoring solution that you might customise to be per-account or whatever else is available in the HTTP request header.


Share:

Friday, 5 October 2012

REST Web Service API HTTP Response Status Codes

What HTTP status codes should your REST web service API be returning to clients?  Does it matter?  Before we launch into this topic, a quick recap of some interesting HTTP status codes:

200 - "OK"  All is well
204 - "No Content"  Nothing returned, but all is still well
400 - "Bad Request"  There is problem on the client's side
500 - "Internal Server Error" There is a problem on the server side
301 - "Moved Permanently" The resource has moved
303 - "See Other Server" Returns a URI to another resource
404 - "Not Found" Server has no clue what the client is asking for
409 - "Conflict" Client has tried to perform an operation that would leave one or more resources in an inconsistent state
401 - "Unauthorized" Client attempted access to a resource without providing the necessary authentication credentials
403 - "Forbidden" Client is not authorised to access a resource

Share:

REST Web Service API - Naming Guidelines

The following offers a suggested set of URI naming guidelines for REST web service APIs that have worked for me in practice.

The book RESTful Web Services RESTful Web Services defines three basic rules for url design which act as a great starting point:
  • Use path variables to encode hierarchy: /parent/child 
  • Put punctuation characters in path variables to avoid implying hierarchy where none exists: /parent/child1;child2 
  • Use query variables to imply inputs into an algorithm, for example: /search?q=jellyfish&start=20 
Share:

Thursday, 4 October 2012

Tuesday, 31 July 2012

REST Web Service API Documentation using RESTdoclet

IG Group has open-sourced RESTdoclet, a maven plugin for generating web-based REST API documentation from REST Java web services implemented using the Spring REST framework.

The plugin:

·         supports Spring 3 REST annotations and JavaDoc out of the box,
·         does not require any additional annotations,
·         is easily integrated with Maven continuous build processes, with minimal configuration,
·         supports multiple streams of service development, and
·         publicises documentation in an interactive, Javadoc-like form, to the web, thus providing a source-code agnostic guide to service consumers.
Share: