Article
· Jun 16, 2023 10m read

Creating a REST service in IRIS

One of the most common needs of our clients is the creation of REST services that allow access to the information present in IRIS / HealthConnect. The advantage of these REST services is that it allows the development of custom user interfaces with the most current technologies taking advantage of the reliability and performance of IRIS in the back-end.

In today's article we are going to create a web service step by step that will allow us to both store data in our database and later consult them. In addition, we are going to do it by configuring a production that allows us to control the flow of messages that we are receiving at all times and thus be able to control its correct operation.

Before starting, just tell you that you have all the code available on Open Exchange so that you can replicate it as many times as you need, the project is configured in Docker, using the IRIS Community so that you don't have to do anything more than deploy it.

Alright, let's get started.

Environment preparation

Before starting with the configuration of the REST service we must prepare our development environment, we must know what information we are going to receive and what we are going to do with it. For this example we have decided that we are going to receive personal data in the following JSON format:

{
    "PersonId": 1,
    "Name": "Irene",
    "LastName": "Dukas",
    "Sex": "Female",
    "Dob": "01/04/1975"
}

As one of the objectives is to store the information we receive, we are going to create an Objectscript class that allows us to register the information in our IRIS. As you can see, the data is quite simple, so the class will not have much complication:

Class WSTEST.Object.Person Extends %Persistent
{

/// ID of the person
Property PersonId As %Integer;
/// Name of the person
Property Name As %String;
/// Lastname of the person
Property LastName As %String;
/// Sex of the person
Property Sex As %String;
/// DOB of the person
Property Dob As %String;
Index PersonIDX On PersonId [ PrimaryKey ];
}

Perfect, we already have our class defined and we can start working with it.

Creation of our endpoint

Now that we have defined the data class with which we are going to work, it is time to create our Objectscript class that will work as an endpoint that will be called from our front-end. Let's see the example class we have in our project step by step:

Class WSTEST.Endpoint Extends %CSP.REST
{

Parameter HandleCorsRequest = 0;
XData UrlMap [ XMLNamespace = "https://www.intersystems.com/urlmap" ]
{
<Routes>
	<Route Url="/testGet/:pid" Method="GET" Call="TestGet" />
	<Route Url="/testPost" Method="POST" Call="TestPost" />
</Routes>
}

ClassMethod OnHandleCorsRequest(url As %String) As %Status
{
	set url = %request.GetCgiEnv("HTTP_REFERER")
    set origin = $p(url,"/",1,3) // origin = "http(s)://origin.com:port"
    // here you can check specific origins
    // otherway, it will allow all origins (useful while developing only)
	do %response.SetHeader("Access-Control-Allow-Credentials","true")
	do %response.SetHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS")
	do %response.SetHeader("Access-Control-Allow-Origin",origin)
	do %response.SetHeader("Access-Control-Allow-Headers","Access-Control-Allow-Origin, Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control")
	quit $$$OK
}
// Class method to retrieve the data of a person filtered by PersonId
ClassMethod TestGet(pid As %Integer) As %Status
{
    Try {
        Do ##class(%REST.Impl).%SetContentType("application/json")
        If '##class(%REST.Impl).%CheckAccepts("application/json") Do ##class(%REST.Impl).%ReportRESTError(..#HTTP406NOTACCEPTABLE,$$$ERROR($$$RESTBadAccepts)) Quit
        // Creation of BS instance
        set status = ##class(Ens.Director).CreateBusinessService("WSTEST.BS.PersonSearchBS", .instance)

        // Invocation of BS with pid parameter
        set status = instance.OnProcessInput(pid, .response)
       	if $ISOBJECT(response) {
            // Sending person data to client in JSON format
        	Do ##class(%REST.Impl).%WriteResponse(response.%JSONExport())
		}
        
    } Catch (ex) {
        Do ##class(%REST.Impl).%SetStatusCode("400")
        Do ##class(%REST.Impl).%WriteResponse(ex.DisplayString())
        return {"errormessage": "Client error"}
    }
    Quit $$$OK
}
// Class method to receive person data to persist in our database
ClassMethod TestPost() As %Status
{
    Try {
        Do ##class(%REST.Impl).%SetContentType("application/json")
        If '##class(%REST.Impl).%CheckAccepts("application/json") Do ##class(%REST.Impl).%ReportRESTError(..#HTTP406NOTACCEPTABLE,$$$ERROR($$$RESTBadAccepts)) Quit
        // Reading the body of the http call with the person data
        set bodyJson = %request.Content.Read()
        
        // Creation of BS instance
        set status = ##class(Ens.Director).CreateBusinessService("WSTEST.BS.PersonSaveBS", .instance)
       	#dim response as %DynamicObject
        // Invocation of BS with person data
        set status = instance.OnProcessInput(bodyJson, .response)
        
        if $ISOBJECT(response) {
            // Returning to the client the person object in JSON format after save it
            Do ##class(%REST.Impl).%WriteResponse(response.%JSONExport())
	    }
        
    } Catch (ex) {
        Do ##class(%REST.Impl).%SetStatusCode("400")
        Do ##class(%REST.Impl).%WriteResponse(ex.DisplayString())
        return {"errormessage": "Client error"}
    }
    Quit $$$OK
}

}

Don't worry if it seems unintelligible to you, let's see the most relevant parts of our class:

Class declaration:

Class WSTEST.Endpoint Extends %CSP.REST

As you can see, our WSTEST.Endpoint class extends %CSP.REST, this is necessary to be able to use the class as an endpoint.

Routes definition:

XData UrlMap [ XMLNamespace = "https://www.intersystems.com/urlmap" ]
{
<Routes>
	<Route Url="/testGet/:pid" Method="GET" Call="TestGet" />
	<Route Url="/testPost" Method="POST" Call="TestPost" />
</Routes>
}

In this code snippet we are declaring the routes that can be called from our front-end.

As you can see, we have two declared routes, the first of which will be a GET call in which we will be sent the pid parameter that we will use to search for people by their identifier and that will be managed by the ClassMethod TestGet. The second call will be of the POST type in which we will be sent the information of the person that we have to record in our database and that will be processed by the ClassMethod TestPost.

Let's take a look at both methods:

Retrieving data of a person:

ClassMethod TestGet(pid As %Integer) As %Status
{
    Try {
        Do ##class(%REST.Impl).%SetContentType("application/json")
        If '##class(%REST.Impl).%CheckAccepts("application/json") Do ##class(%REST.Impl).%ReportRESTError(..#HTTP406NOTACCEPTABLE,$$$ERROR($$$RESTBadAccepts)) Quit
        // Creation of BS instance
        set status = ##class(Ens.Director).CreateBusinessService("WSTEST.BS.PersonSearchBS", .instance)

        // Invocation of BS with pid parameter
        set status = instance.OnProcessInput(pid, .response)
       	if $ISOBJECT(response) {
            // Sending person data to client in JSON format
        	Do ##class(%REST.Impl).%WriteResponse(response.%JSONExport())
		}
        
    } Catch (ex) {
        Do ##class(%REST.Impl).%SetStatusCode("400")
        Do ##class(%REST.Impl).%WriteResponse(ex.DisplayString())
        return {"errormessage": "Client error"}
    }
    Quit $$$OK
}

In this method you can see how we have declared in our ClassMethod the reception of the pid attribute that we will use in the subsequent search. Although we could have done the search directly from this class, we have decided to do it within a production to be able to control each of the operations, which is why we are creating an instance of the Business Service WSTEST.BS.PersonSearchBS to which we later call its method OnProcessInput with the received pid. The response that we will receive will be of the WSTEST.Object.PersonSearchResponse type that we will transform into JSON before sending it to the requester.

Storing a person's data:

ClassMethod TestPost() As %Status
{
    Try {
        Do ##class(%REST.Impl).%SetContentType("application/json")
        If '##class(%REST.Impl).%CheckAccepts("application/json") Do ##class(%REST.Impl).%ReportRESTError(..#HTTP406NOTACCEPTABLE,$$$ERROR($$$RESTBadAccepts)) Quit
        // Reading the body of the http call with the person data
        set bodyJson = %request.Content.Read()
        
        // Creation of BS instance
        set status = ##class(Ens.Director).CreateBusinessService("WSTEST.BS.PersonSaveBS", .instance)
       	#dim response as %DynamicObject
        // Invocation of BS with person data
        set status = instance.OnProcessInput(bodyJson, .response)
        
        if $ISOBJECT(response) {
            // Returning to the client the person object in JSON format after save it
            Do ##class(%REST.Impl).%WriteResponse(response.%JSONExport())
	    }
        
    } Catch (ex) {
        Do ##class(%REST.Impl).%SetStatusCode("400")
        Do ##class(%REST.Impl).%WriteResponse(ex.DisplayString())
        return {"errormessage": "Client error"}
    }
    Quit $$$OK
}

As in the previous case, we could have saved our person object directly from this class, but we have decided to do it from a Business Operation that will be called from the Business Service WSTEST.BS.PersonSaveBS.

As you can see in the code we are retrieving the information sent by the client in the POST call by reading the Stream present in %request.Content. The string obtained will be what we will pass to the Business Service.

 

Publishing our Endpoint

To avoid taking this article forever, we are going to ignore the explanation related to production, you can review the code directly in the OpenExchange project. The production that we have configured is as follows:

We have 2 declared Business Services, one to receive search requests and another for storage requests of the person's data. Each of them will invoke their appropriate Business Operation.

Perfect, let's review what we have configured in our project:

  • 1 endpoint class that will receive client requests (WSTest.Endpoint)
  • 2 Business Services that will be called from our endpoint class (WSTest.BS.PersonSaveBS and WSTest.BS.PersonSearchBS).
  • 2 Business Operations in charge of carrying out the search and recording of the data (WSTest.BS.PersonSaveBS and WSTest.BS.PersonSearchBS)
  • 4 classes to send and receive data within the production that extend from Ens.Request and Ens.Response (WSTest.Object.PersonSearchRequestWSTest.Object.PersonSaveRequestWSTest.Object.PersonSearchResponse WSTest.Object.PersonSaveResponse).

We only have one last step left to put our web service into operation and that is its publication. To do this, we will access the Management Portal option System Administration -->  Security -> Applications -> Web Applications

We will see a list of all the Web Applications configured in our instance:

Let's create our web application:

Let's go over the points we need to configure:

  • Name: We will define the route that we are going to use to make the invocations to our service, for our example it will be /csp/rest/wstest
  • Namespace: the namespace on which the web service will work, in this case we have created WSTEST in which we have configured our production and our classes.
  • Enable Application: enabling the web service to be able to receive calls.
  • Enable - REST: When selecting REST we indicate that this web service is configured to receive REST calls, when selecting it we must define the Dispatch Class that will be our endpoint class WSTEST.Endpoint.
  • Allowed Authentication Methods: configuration of the authentication of the user who makes the call to the web service. In this case we have defined that it be done through Password, so in our Postman we will configure the Basic Authorization mode in which we will indicate the username and password. We have the option of defining the use of JWT Authentication which is quite useful as it does not expose the user data and password in REST calls, if you are interested in delving into JWT you can consult this article.

Once we finish configuring our web application we can launch a couple of tests by opening Postman and importing the WSTest.postman_collection.json file present in the project.

Testing our Endpoint

With everything configured in our project and production started, we can launch a couple of tests on our web service. We have superuser configured as the requesting user so we won't have problems in order to save and retrieve data. In case of using a different user, we must make sure that either he has the necessary roles assigned or we assign them in the Application Roles tab of the definition of our web application.

Let's start by recording someone in our database:

We have received a 200, so it seems that everything went well, let's check the message in production:

Everything has gone well, the message with the JSON has been correctly received in the BS and has been successfully recorded in the BO.

Now let's try to recover the data of our beloved Alexios Kommenos:

Bingo! There is Alexios with all the information about him. Let's check the message in production:

Perfect, everything has worked as it should. As you have seen, it is really easy to create a REST web service in IRIS, you can use this project as a base for your future developments and if you have any questions, don't hesitate to leave a comment.

Discussion (0)1
Log in or sign up to continue