REST API


About the REST API


The Jiwa 7 REST API is a restful web service providing a means to interact with the Jiwa database and business logic via HTTP verbs.

The bulk of the REST API is provided by a Jiwa plugin.  A windows service and web deployment package provide the mechanism to host the service, but the routes and the logic behind each route are defined in the plugin. Additional or alternative routes and logic can be provided by an additional plugin or plugins. See Adding Custom Routes to the REST API for information on this.

The Jiwa 7 REST API uses the ServiceStack framework. It produces not only a pure HTTP web service, accessible by any HTTP-capable client, but also has support for strongly typed clients:

 You don't need to use a ServiceStack client to consume the REST API - as it is a pure HTTP REST service - but the ServiceStack clients bring the benefit of smaller, cleaner code and strong typing such that many mistakes are caught at compile time rather than runtime.


Minimum Requirements


The REST API requires SQL Server 2012 or later and Jiwa 7.01.00 or later.


Use Cases


Typical use cases for the REST API Are:

  • Integrate a web store to Jiwa
  • Field sales via a mobile device (iOS/Android/UWA)
  • Integrate Jiwa and Point Of Sale systems
  • Provide intranet services to staff via a web browser
  • Provide specialised browser based interfaces for tailored, streamlined operational workflows.


Hosting Options


There are two options available for hosting the Jiwa REST API:

Self Hosted

The self hosted option is a windows service.  The service is installed when Jiwa 7 is installed.

IIS

If you wish to use an IIS server then the Jiwa 7 installation includes a Web Package that can be imported to IIS.

IIS with Reverse Proxy to Self Hosted

See this article on how to have IIS act as a reverse proxy to the Jiwa ReST API self hosted service.


Deployment and Configuration


The first step to installation is to enable the REST API plugin in Jiwa.

Open the Plugin Maintenance form, locate the REST API plugin and check the "Enabled" checkbox, then press the save button on the ribbon. Exit Jiwa and log back in, and then open the System configuration form.

There are three system settings introduced by the plugin:

The SessionExpiryInMinutes specifies how many minutes elapse since the last API call was received before expiring the session and logging the user out.

The DebugMode indicates if stack traces are to be returned in error responses, and if requests should be logged.

The AutoQueryMaxLimit limits the number of rows that can be returned by an auto query - this is good for preventing inadvertent denial-of-service (dos) through a wayward query.


Self Hosted

If using a self hosted solution, Jiwa must be installed on the machine to host the service.

Locate the Jiwa Financials program folder (%Program Files (x86)%/Jiwa Financials/Jiwa) and edit the JiwaAPISelfHostedService.exe.config file.  The default configuration looks like the following:

Default Configuration
<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<startup> 
		<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
	</startup>
	<appSettings>
		<add key="ServerName" value="localhost" />
		<add key="DatabaseName" value="JiwaDemo" />
		<add key="JiwaUsername" value="api" />
		<add key="JiwaPassword" value="password" />
		<add key="URLBase" value="http://*:80/" />
	</appSettings>
</configuration>

The appSettings section has the value which will need to be edited.  Change the value attribute contents for each of the keys ServerName, DatabaseName, Jiwausername, JiwaPassword and URLBase.  The keys are explained in the following table.

KeyDescription
ServerNameThe name of the SQL Server
DatabaseNameThe database name
JiwaUsername

The Jiwa user for the service to initially connect to. The service will use this username to connect to Jiwa once at service start, and it then disconnects.

It is recommended to have a named licence for this user.

As of Jiwa version 7.00.186.00 Named licences have been deprecated. Instead a specific user is linked to a licence via the Licence maintenance form.

JiwaPassword The password for the user
URLBase

The base url. The default value of http://*:80/ indicates all site names running on the local machine, on port 80 will work. So http://localhost for use within the firewall, and if a port forward is configured then any port 80 traffic will be accepted. To restrict to a specific domain replace the * with the domain name - for example: http://example.com:80/

The trailing forward slash is important! Make sure your URLBase ends with a /

Ensure that there are no other services (i.e. a local web-server such as IIS) already listening on the port you choose, otherwise the Windows services will error upon starting.

Now open services.msc and edit the properties of the Jiwa 7 Self Hosted REST API service - right click on the service and select "Properties" from the context menu:

On the General tab, change the Startup Type to be Automatic (Delayed Start)

On the Log On tab, select Log on as to be the Local System account

On the Recovery tab, change the FirstSecond and Subsequent failures to be "Restart the Service".

Press Apply and then back on the General tab press the Start button.  If the service fails to start, check the event log for any information relating to the service.


You can then check to see if the service is working by opening a browser and entering "localhost" in the address bar.

IIS

If using IIS, Jiwa must be installed on the machine to host the service.

Open IISManager, expand the server and right click on the Sites node and select Add Web Site... from the context menu


In the Add Web Site dialog which appears, enter the Site name "JiwaAPI" and select a physical path

Press OK.

If IIS warns you that another site is bound on the port, you can provide a different port, or a host name - or stop the conflicting site in IIS Manager.

HTTPS/SSL

It is recommended to use HTTPS (Port 443) - If you choose HTTPS as the binding type, you will need to specify a previously imported server certificate.


The creation of the site above will have created an Application Pool of the same name as the site (JiwaAPI) - but the .NET Framework version may be set to 2.0 instead of the required 4.0 (depending on your version of IIS), and the Enable 32-Bit Applications setting will be off. Change the .NET Framework Version for the pool to be v.40, and set Enable 32-Bit Applications to True


If using a Windows Server Operating System:


Open an elevated command prompt (run CMD as Administrator), and change the current directory to the location of the JiwaAPI folder under the Jiwa 7 program folder (%ProgramFiles(x86)%/Jiwa Financials/Jiwa 7/JiwaAPI).

Run the following command:

C:\Program Files (x86)\Jiwa Financials\Jiwa 7\JiwaAPI>JiwaAPI.deploy.cmd /T

The /T option above tells the deploy script to not actually deploy, but run in test mode and report any problems without leaving a mangled install.  Inspect the output and make sure there are no errors.

If there are no errors, run the command with /Y instead of /T:

C:\Program Files (x86)\Jiwa Financials\Jiwa 7\JiwaAPI>JiwaAPI.deploy.cmd /Y

If the above command yields an error that msdeploy.exe is not found, then you must install that first - https://www.iis.net/downloads/microsoft/web-deploy

If you have installed msdeploy.exe and then when running they JiwaAPI.deploy.cmd get an error "\Jiwa was unexpected at this time, then you can work around that running this command instead (found withing JiwaAPI.deploy.cmd):

"C:\Program Files (x86)\IIS\Microsoft Web Deploy V3\msdeploy.exe" -source:package='JiwaAPI.zip' -dest:auto -verb:sync -disableLink:AppPoolExtension -disableLink:ContentExtension -disableLink:CertificateExtension

Run the above from within the C:\Program Files (x86)\Jiwa Financials\Jiwa 7\JiwaAPI folder.


If using Windows 10 + IIS:

Locate the JiwaAPI.zip file in the JiwaAPI folder of the Jiwa 7 program folder (%ProgramFiles(x86)%/Jiwa Financials/Jiwa 7/JiwaAPI).

Extract just the contents of just the PackageTmp folder to the Physical Path used in the Add Web Site dialog previously (eg: C:\inetpub\JiwaAPI).

The folder structure should look like the following:


Also with Windows 10, make sure the Windows Features "Application Development Features" have been enabled via the Control Panel:



Once the above step is completed locate the Web.Config file, located in the Physical Path used in the Add Web Site dialog previously. Open the file with a text editor (such as Notepad). The default configuration contains an applicationSettings section which looks like the following:

<applicationSettings>
    <JiwaAPI.Properties.Settings>
      <setting name="ServerName" serializeAs="String">
        <value>localhost</value>
      </setting>
      <setting name="DatabaseName" serializeAs="String">
        <value>JiwaDemo</value>
      </setting>
      <setting name="JiwaUsername" serializeAs="String">
        <value>api</value>
      </setting>
      <setting name="JiwaPassword" serializeAs="String">
        <value>password</value>
      </setting>
    </JiwaAPI.Properties.Settings>
  </applicationSettings>

Change the settings as appropriate - the following table describes each setting.

Setting NameDescription
ServerNameThe name of the SQL Server
DatabaseNameThe database name
JiwaUsername

The Jiwa user for the service to initially connect to. The service will use this username to connect to Jiwa once at service start, and it then disconnects.

It is recommended to have a named licence for this user.

As of Jiwa version 7.00.186.00 Named licences have been deprecated. Instead a specific user is linked to a licence via the Licence maintenance form.

JiwaPassword The password for the user

Save the changes made to the web.config file. Start the IIS Site from within IIS Manager - right click the JiwaAPI site, select Manage Web Site then Start.


You can then check to see if the service is working by opening a browser and entering "localhost" in the address bar.



Setting Route Permissions


Once the service is running, permissions must be set within Jiwa to specify which user groups can access which routes.  This is done via the User Group Maintenance form in Jiwa.

Load the User Group Maintenance form

Default REST API Permission

In the Group Information section of the form, there is a field labelled "Default REST API Permission".  This can be one of 3 values - Undefined, Allow or Disallow.

When set to Disallow, all users belonging to that user group will not be able to invoke any route, regardless of other permissions

When set to Allow, users belonging to that user group will be able to invoke any route - provided they are not a member of another group which disallows, or an explicit route permission is set to disallow.

When set to Undefined, users belonging to that user group will be unable to invoke any route - unless they are a member of another group which allows, or an explicit route permission is set to allow, and belong to no groups where the default or route permission is disallow.

Explicit Route / Path Permission

Explicit permissions per route can be made for a User Group. In the "Import Path" field of the REST API tab of User Group Maintenance, enter the URL of the REST API followed by /RestPaths and press the Import button.  This will visit the REST API and retrieve a list of all routes:

Then permissions can be set per route.

Adding Custom Routes


See Adding Custom Routes to the REST API for information on how to extend the REST API to add your own custom routes.

Testing the API


Once you have the REST API running, it can quickly be tested using the SwaggerUI which is deployed by default.  This is a browser interface for calling the routes.

When you open a browser to the location of your api, it by default opens on the metadata page.  At the bottom of this are some links - one of them is a link to the the Swagger UI


Clicking on the Swagger UI link will take you to the Swagger UI, built on the Open API specification document.


Most operations require authentication, so click on the auth group to expand it:


Then click on the /auth route to expand that:


Scroll down to the Parameters and fill out the UserName and Password fields:

Then scroll down and press the "Try it Out!" button.  You should see a response come back:


Now that you are authenticated, you can visit other routes - for example to retrieve a list of products, visit the /Inventory route and use the GET method:


Securing the API


Best practices for securing your API are:

  • Turn off Debug Mode system setting.  Leaving this on logs to request logs all requests - including credentials - and exposes a route to query and inspect the logs.
  • If using the Self Hosted service, don't run as a Windows Administrator account.  Create a dedicated Windows User to run as.
  • Don't set allow permissions on every route - only permit what is needed.
  • If giving customers access to your API, give them Debtor API Keys and not Staff API Keys.
  • Don't use a privileged Jiwa user account for API Keys (don't give admin users API keys).
  • Use an auto-renewing SSL Certificate.  Lets Encrypt is a free service which can be used to generate, install and renew SSL certificates.
  • If you do not need to publicly expose your API, then don't.
  • If you do need to publicly expose your API, consider a whitelisted IP address access policy - for instance if your API is only ever accessed by a web store, then whitelist the IP of that web store.
  • Consider using a front-end proxy such as Cloudflare.  Services such as Cloudflare can filter out malicious traffic before it reaches your API.
  • Consider employing rate limiting. The optional plugin REST API Rate Limit can be used to set limits on how often an IP address can call the API in a configurable time interval.

SSL Certificates

Recommended practice is to use an SSL certificate for all http traffic, so the environment should be configured such that the Jiwa REST API also uses SSL.

When using the Jiwa self hosted REST API service, it is a Windows environment configuration to install and bind the certificate.  Once the environment is configured for SSL, all that is needed for the Jiwa configuration is to use the https prefix and correct hostname and port for the URLBase configuration setting in the JiwaAPISelfHostedService.exe.config.

Tools such as the free Win-Acme client can be used to generate, install and renew automatically certificates using the Lets Encrypt service, and these tools will also add the binding necessary for the certificate.  If using IIS, then the IIS Manager should be used to bind a certificate to the hostname and port.

To view which certificates are installed, you can use certlm.msc (the Local Machine Certificate Manager).

Typically certificates will be found in the Personal (MY) store.

The certificate must be a valid, current (not expired) certificate, or else clients consuming the API will likely refuse or drop the connection.

To view the bindings for the certificates, use an elevated command prompt (run as Administrator) and the following command:

netsh http show sslcert

If the binding desired is not present, add one with the following command:

netsh http add sslcert hostnameport=api.jiwa.com.au:443 certhash=4a3b19ddaa7956fb511aebc9feaa28ab4ff6d0ee appid={91c8a897-2234-46a7-8adc-ace477f87e54} certstorename=MY

Obviously you would change the hostname, port, certhash and certstore name to suit your own environment.

The certhash is the Certificate Hash and can be obtained from the netsh command to view certificates, or by double-clicking the certificate in the certlm.msc to open the Certificate dialog and locating the Thumbprint property of the Details tab.

If you find there is a binding which you want to remove (perhaps an expired certificate), then you can do that with:

netsh http del sslcert hostnameport=api.jiwa.com.au:443

Again, substitute the appropriate values with your own.

Depending on your DNS configuration, you may also wish to edit the Hosts file on the machine running the REST API service, so that the DNS name for the API resolves to the local machine.  This will allow the FQDN to be accessible on the machine running the REST API service - which may be useful in debugging or testing.  The hosts file is found in the C:\Windows\System32\drivers\etc folder.