Jun 30, 2013

Mocking REST services using Apache HTTPD

We needed the ability to run our application using mock-data, but due to the complexity of our data-sources, we could not mock data or data sources. We did however have RESTful web services that exposed the domain data as Web Resources, these services are invoked by the Application Tier to present UI. We found that it was easier to mock our REST services than having to create a new data source with mock data.

We configured Apache Webserver ( HTTPD) to simulate the REST resources with the resource URLs that matches the actual service URLs. For a service resource: http://servicehost:8080/services/mydomain/users/test01/profile, that returns a JSON object for the user's profile, we created a "profile" file, containing the desired JSON, under /htdocs/services/mydomain/users/test01. The file can be accessed via the URL: http://httpdhost:80/service/mydomain/users/test01/profile that matches the actual service URL except for hostname and port.

Apache HTTPD was configured to return response content-type as application/json instead of default text/plain for the required directories. This was done by setting the httpd conf ForceType for a Location to set a particular content type.
<Location /services>
  ForceType application/json
</Location>

So, by changing the external parameter for the services URL (hostname and port) to a mock service provider (HTTPD), one can run the application using mock data.

We found this simple approach particularly useful in our development environment where there is an independent UI development team. UI developers can now develop and test the UI using desired mock data without being dependent on services to be available or having to create a mock data at each service-call level. 
It's easier for them to manage and change JSON (JavaScript Object Notation) as oppose to mock-data approach where they would need to understand the underlying data source and data representation. Also, the mock configuration is managed as single switch ie an  externalized application parameter (service URL), as oppose to changing all the data-stores (service URLs) in the UI code.

I got some good insight and validation for the REST service design when I started creating the resources in htdocs directory structure.

No comments:

Post a Comment