Article
· Dec 3, 2021 7m read

ObjectScript REST API Cookbook

Creating REST API using InterSystems ObjectScript is very easy, but some recipes can help you into this process:

1) To create your REST API extends %CSP.REST and Go to System Administration > Security > Applications > Web Applications > Click the button Create New Web Application and set the Name, REST Dispatch Class with your package and classname and choose the Allowed Authetication Methods. See this example:

 
Edit Web Application

2) Configure your REST API using ZPM configuration. To do this follow this sample (watch the tag <CSPApplication>):

 
ZPM Code to Create REST API

3) To Enable CORS (call the API from a different server or domain out the API domain), set the Parameter HandleCorsRequest = 1

4) To set the Content Type use: Parameter CONTENTTYPE = "application/json"

5) To set the Charset use: Parameter CHARSET = "utf-8"

6) To intercept the requests to the API and do something before the request processing, override the ClassMethod OnPreDispatch and do validations, enrich header and content of the request, for example. See a sample (watch pContinue, is possible interrupt the processing if you set pContinue = 0):

 
OnPreDispatch sample

7) To change Access Management to the API override the Class Method AccessCheck, and set pAuthorized = 0 to deny access and 1 to grant access. See the sample:
 

 
Deny or grant access based into rules configured into XData declaration

8) To set HTTP Code, override the Class Method ReportHttpStatusCode. See the sample:

 
Spoiler

9) To generate the swagger documentation to your REST API, write comments above the your Class Methods and above your REST mappings and implement the Method SwaggerSpec. See:

 
Swagger Documentation generation

10) To mapping your endpoint to your REST API follow the Intersystems document https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls?KEY=GREST_csprest#GREST_urlmap_map and see this sample:
 

 
REST API Mapping Sample

11) To get query parameters use: %request.CgiEnvs(HeaderKey), where header key is the name of the query string.

 

To see these tips in action, download and use my app, Security Mediator in: https://openexchange.intersystems.com/package/API-Security-Mediator

Discussion (2)4
Log in or sign up to continue