Find

Question
· 5 min ago

Defining REST API using iris-rest-api-template - Need guidance

Defining my first REST API within InterSystems using iris-rest-Api-template as a basis and I am seeing if someone could provide me some guidance to see if I can make it work.  

In some of my other posts, I have been trying to come up with a way for our Enterprise Application Development team which works with .Net to build Applications to make a REST call to our instance of InterSystems to query some of the Cache Tables we have defined. 

Using the iris-rest-api-template, I have created the osuwmc.DataLookup.REST.Base.cls

Class osuwmc.DataLookup.REST.Base Extends %CSP.REST [ System = 3 ]
{

Parameter CHARSET = "utf-8";
Parameter CONTENTTYPE = "application/json";
Parameter HandleCorsRequest = 1;
Parameter PAGESIZE As INTEGER = 50;
ClassMethod OnPreDispatch(pUrl As %String, pMethod As %String, ByRef pContinue As %Boolean) As %Status
{
  SET tSC = $$$OK
  TRY {
    
    // Set the return type according to the Accept type in the request. Default is application/json.
    IF ('..AcceptsContentType(..#CONTENTTYPEJSON)) {
      SET tSC = ..ReportHttpStatusCode(..#HTTP406NOTACCEPTABLE), pContinue=0
      QUIT
        } ELSE {   
      // This always returns json
      SET %response.ContentType=..#CONTENTTYPEJSON
        }
        
        
        // read request object into %DynamicObject format
    IF ((pMethod'="POST") && (pMethod'="PUT")) || (%request.Content="") {
      SET %request.Content = {}
    } ELSE {
      IF '$isobject(%request.Content) {
        SET tContent = %request.Content
      } ELSE {
        SET tContent = ""
        WHILE '%request.Content.AtEnd {
          SET tContent = tContent_%request.Content.Read()
        }
      }
      IF (tContent="") {
        SET %request.Content = {}
      } ELSE {
        SET tContent = $zconvert(tContent, "I", "UTF8")
        SET %request.Content = ##class(%Library.DynamicObject).%FromJSON(tContent)
      }
    }
        
  } CATCH ex {
    SET tSC = ex.AsStatus()
  }
  QUIT ##class(%iKnow.REST.Base).%ErrorHandler(tSC, .pContinue)
}

ClassMethod %ProcessResult(pStatus As %Status = {$$$OK}, pResult As %DynamicObject = "") As %Status [ Internal ]
{
  #dim %response As %CSP.Response
  SET tSC = $$$OK
  IF $$$ISERR(pStatus) {
    SET %response.Status = 500
    SET tSC = ..StatusToJSON(pStatus, .tJSON)
    IF $isobject(tJSON) {
      SET pResult = tJSON
    } ELSE {
      SET pResult = { "errors": [ { "error": "Unknown error parsing status code" } ] }
    }
  } 
  ELSEIF pStatus=1 {
    IF '$isobject(pResult){
      SET pResult = {
      }
    }
  }
  ELSE {
    SET %response.Status = pStatus
    SET error = $PIECE(pStatus, " ", 2, *)
    SET pResult = {
      "error": (error)
    }
  }
  
  IF pResult.%Extends("%Library.DynamicAbstractObject") {
    WRITE pResult.%ToJSON()
  }
  ELSEIF pResult.%Extends("%JSON.Adaptor") {
    DO pResult.%JSONExport()
  }
  ELSEIF pResult.%Extends("%Stream.Object") {
    DO pResult.OutputToDevice()
  }
  
  QUIT tSC
}

ClassMethod ReportHttpStatusCode(pHttpStatus, pSC As %Status = {$$$OK}) As %Status
{
  Set %response.Status=pHttpStatus
  
  If $$$ISERR(pSC) Do ..outputStatus(pSC)
  /*
  If (+pHttpStatus>=400) {
    Set %response.ContentType = "application/json"
    SET pResult = {
      "error": ($PIECE(pHttpStatus, " ", 2, *))
    }
    Return ..%ProcessResult($$$OK, pResult)
  }*/
  Return $$$OK
}

}

and the osuwmc.DataLookup.REST.TableLookup

Class osuwmc.DataLookup.REST.TableLookup Extends osuwmc.DataLookup.REST.Base
{

Parameter Version = "1.0.0";
Parameter GlobalName = "^OSUWMCDataLookup.TableLookup";
XData UrlMap [ XMLNamespace = "http://www.intersystems.com/urlmap" ]
{
<Routes>  
    <!-- Server Info -->
    <Route Url="/" Method="GET" Call="GetInfo" Cors="true"/>
    <Route Url="/info" Method="GET" Call="GetAllEpicDepartments" Cors="true"/>
    </Routes>
}

ClassMethod GetInfo() As %Status
{
    SET version = ..#Version
    SET info = {
      "version": (version)
    }
    RETURN ..%ProcessResult($$$OK, info)
}

ClassMethod GetAllEpicDepartments() As %Status
{
    SET tSC = $$$OK
    set sql = "SELECT ID as DepartmentID, Abbr, Name, ExternalName, PhoneNumber, ApptPhone, FaxNumber, Address1, Address2, City, Zip, Specialty, RevLocID, RevLocName, BuildingCategoryID, BuildingName, DepCategoryTypeID, DepType, Center, EAFParent, CostCenter FROM osuwmc_Epic_Clarity.DepartmentMaster"
    do ##class(%ZEN.Auxiliary.jsonSQLProvider).%WriteJSONFromSQL(,sql)
    return tSC
}

ClassMethod GetEpicDepartment(ID As %String) As %Status
{
    SET tSC = $$$OK
    set sql = "SELECT ID as DepartmentID, Abbr, Name, ExternalName, PhoneNumber, ApptPhone, FaxNumber, Address1, Address2, City, Zip, Specialty, RevLocID, RevLocName, BuildingCategoryID, BuildingName, DepCategoryTypeID, DepType, Center, EAFParent, CostCenter FROM osuwmc_Epic_Clarity.DepartmentMaster WHERE ID = ?"
    do ##class(%ZEN.Auxiliary.jsonSQLProvider).%WriteJSONFromSQL(,,sql,ID)
    return tSC
}
ClassMethod SwaggerSpec() As %Status
{
  Set tSC = ##class(%REST.API).GetWebRESTApplication($NAMESPACE, %request.Application, .swagger)
  Do swagger.info.%Remove("x-ISC_Namespace")
  Set swagger.basePath = "/crud"
  Set swagger.info.title = "REST API to Access and Query OSUWMC Cache Tables"
  Set swagger.info.version = "0.1"
  Set swagger.host = "intengtest.osumc.edu"
  Return ..%ProcessResult($$$OK, swagger)
}

}

I defined the Web Application as /api/mgmnt/<namespace>/TableLookup with the osuwmc.DataLookup.REST.TableLookup as the Dispatch Class.

When I try to execute the REST call using POSTMAN, "msg": "ERROR #8754: Unable to use namespace: TABLELOOKUP."

If I try to use the sample class, I get a message saying that "The request URL was not found on the server" or a "404 Not Found"

I checked the Web Gateway to make sure the application was defined.

So, am I missing a step somewhere?

Discussion (0)1
Log in or sign up to continue
Article
· 3 hr ago 3m read

embeddedpy-bridge: Um kit de ferramentas para Embedded Python

Embeddedpy-bridge: Um kit de ferramentas para Embedded Python

Visão geral

Embedded Python é um divisor de águas para o InterSystems IRIS, oferecendo acesso ao vasto ecossistema Python diretamente dentro do banco de dados. No entanto, fazer a ponte entre ObjectScript e Python às vezes pode parecer como traduzir entre dois mundos diferentes.

Para tornar essa transição perfeitamente utilizável, embeddedpy-bridge.

Este pacote é um kit de utilidades focado em desenvolvedores, projetado para fornecer wrappers de alto nível em ObjectScript, sintaxe familiar e tratamento de erros robusto para o Python embarcado. Ele permite que os desenvolvedores interajam com estruturas de dados Python usando os padrões nativos do IRIS com os quais já estão acostumados.

O desafio

Embora a biblioteca %SYS.Python seja poderosa, os desenvolvedores frequentemente enfrentam alguns obstáculos:

  1. Tratamento de proxies: navegar por listas e dicionários Python usando proxies brutos não parece algo “nativo” do ObjectScript.
  2. Iteração: laçosWhile padrão do ObjectScript não “conversam” nativamente com iteradores Python.
  3. Gerenciamento de namespaces: garantir que utilitários Python estejam disponíveis em todo o sistema.

A Solução: embeddedpy-bridge

Meu objetivo foi criar uma “Ponte” que faça o Python se sentir como um cidadão de primeira classe dentro do ObjectScript.

Principais recursos:

  • Convenção de Prefixopy : Todos os métodos na classe %ZPython.Utils usam o prefixo py (por exemplo, pyDict(), pyList(), pyJSON()) para diferenciar claramente a lógica relacionada ao Python do código nativo do IRIS.
  • Wrappers Orientados a Objetos (OO): Classes de alto nível para ListDict que suportam métodos familiares como GetAt(), SetAt(), e Count().
  • Iteradores Inteligentes:ListIterator eDictIterator integrados permitem percorrer dados Python usando loops While padrão do ObjectScript.
  • Suporte a Macros: Um arquivo %ZPython.inc fornece atalhos como $$$pyDict$$$pyJSON para um desenvolvimento mais limpo e rápido.

Exempos de uso

1. Sintaxe Simples (Macros)

Chega de digitar ##class(...) toda vez. Use atalhos rápidos:

  • $$$pyDict — Cria um dicionário Python.
  • $$$pyList — Cria uma lista Python.
  • $$$pyJSON(dynObj) — Converte um objeto JSON em Python instantaneamente.

2. Manipulação Unificada de Dicionários

Em vez de lidar com proxies Python puros, use o dicionário encapsulado:

Exemplo de código:

Include %ZPython
Set pyDict = $$$pyDict
Do pyDict.SetAt("Status", "Active")
Do pyDict.SetAt("Version", 1.0)

// Standard IRIS iteration
Set iter = pyDict.%GetIterator()
While iter.%GetNext(.key, .val) {
    Write "Key: ", key, " Val: ", val, !
}

 

Set pyList = $$$zpyList()

Do pyList.Append("First Item")
Do pyList.Append("Second Item")

Write "Total items: ", pyList.Count(), !

// Access by index
Write "Item 1: ", pyList.GetAt(0), !

2. Conversão de Dados Sem Esforço

Converta objetos dinâmicos do IRIS em objetos Python e vice-versa com uma única linha:

Exemplo de código:

Set dynObj = {"name": "John", "roles": ["Admin", "User"]}
Set pyObj = $$$pyJSON(dynObj)

// Verify Python type
Write ##class(%ZPython.Utils).IsType(pyObj, "dict") // 1

O objetivo deste projeto é construir uma ponte entre dois mundos poderosos. Enquanto o InterSystems IRIS fornece o motor para o Python embutido, o embeddedpy-bridge fornece o volante.

Discussion (0)1
Log in or sign up to continue
Announcement
· 4 hr ago

InterSystems Open Exchange Applications Digest, December 2025

Hello and welcome to the December 2025 Open Exchange Recap.
General Stats:
22 new apps in December
571 downloads in December
1,101 applications all time
44,940 downloads all time
3,484 developers joined
New Applications
iris-image-reducer
By Dmitry Maslennikov
IRISConfigurationDiagrams
By XINING MA
iris-airflow-provider
By Muhammad Waseem
iris_io_utility
By Pietro Di Leo
gj :: dataLoader
By John Murray
iris-jsonschema
By Joshua Brandt
Testify
By Ashok Kumar T
sqlancer-iris
By Dmitry Maslennikov
controlf
By Djonata Hortz
dc-toon
By Henry Pereira
iris-global-statistics-chart
By sara aplin
IRISVectorSearchRAGExample
By Emil Polakiewicz
confluent-kafka-iris
By Andrew Sklyarov
iris-localization-lab
By Ashok Kumar T
ConfigSettingsExtract
By Keren Skubach
embeddedpy-bridge
By Ashok Kumar T
VIPIK
By Yannick Daniel Gibson
UDP
By Robert Cemper
workshop-openehr
By Luis Angel Pérez Ramos
fhir-lists
By Netanel Frankel
iris-pgwire
By Thomas Dyar
fhir-profile-demo
By Ashok Kumar T
New Releases
System-Task-REST by Ashok Kumar T
v1.0.1
updated the code
v1.0.2
fixed module file
IrisTest-Fmtserializer by Ashok Kumar T
v1.0.2
Now supports exporting data in TOON
format.
IrisOASTestGen by José Pereira
v0.0.11
  • Support for List and File data types
  • Little documentation improvements for usage
  • Next release: some toy API server implementation for better usage demonstration
v0.0.17
  • Demo with tutorial
  • Added parameter for define package of generated files
  • General fixes
v0.0.27
OPNEx-ECP Deployment by Jose Tomas Salvador
v1.0.1
Github project revisited to make it work with IRIS 2025.3 and the fact that no webserver is deployed by default with IRIS. I took out WebTerminal installation as it's having some issues in 2025.1. Hopefully this is something temporary and I'll introduce it again once the issues are solved.
Test Coverage Tool by Timothy Leavitt
v4.1.2

[4.1.2] - 2025-12-02

Fixed

  • #75: Avoid infinite loop when first class in alphabetical order has a [ Language = python ] method
iris-fhir-template by Evgeny Shvarov
v1.3.5
module version bump
v1.3.6
Added JSONAdvSql support because of this PR
v1.3.7
Made JsonAdvSql as a default data strategy - learn more in docs
integratedml-demo-template by Thomas Dyar
v1.1.0

December 2025 Modernization

What's New

  • Official IRIS image
    : Switched to containers.intersystems.com/intersystems/iris-community:latest-em (valid license, supports up to 20 cores)
  • Multi-architecture
    : ARM64 (Apple Silicon) and AMD64 (Intel) support
  • DB-API driver
    : Replaced JDBC/PyODBC with native intersystems-irispython driver
  • TensorFlow 2.16.1
    : Updated from 2.2.0
  • GitHub Actions CI/CD
    : Automated Docker build testing
  • Docker/Podman support
    : Works with either container runtime

Breaking Changes

  • Folder renamed: tf2-jupyter-jdbctf2-jupyter
  • Notebooks renamed (removed -jdbc/-PyODBC suffixes)
  • Connection code changed from JDBC to DB-API pattern

Removed

  • JDBC driver (intersystems-jdbc-3.1.0.jar)
  • ODBC driver and config files

Fixed

  • IRIS "core limit exceeded" error (expired Docker Hub images)
  • Port documentation (1972, not 51773)
  • Updated architecture diagram
v1.1.1
Notebook Fixes (December 2025) Fixed
IPython deprecation warning: Updated imports from IPython.core.display to IPython.display
VALIDATE MODEL pivot error: Added drop_duplicates() to handle duplicate metric entries before pivot
ED_visit_90_day.ipynb: Completely rewritten with UCI Diabetes 130-US Hospitals dataset (~92k records)
IRIS SQL reserved word: Changed Count alias to RecCount in SQL queries
AutoML matplotlib dependency: Added matplotlib to IRIS Dockerfile for visualization
New Data
Added diabetic_readmission.csv (UCI Diabetes 130-US Hospitals dataset) for ED_visit notebook
All Notebooks Tested
campaign-integratedml.ipynb ✓
readmission-integratedml.ipynb ✓
biomedical-integratedml.ipynb ✓
ED_visit_90_day.ipynb ✓
This release addresses the issues reported by community members regarding notebook execution failures.
IRISFHIRServerLogs by Ashok Kumar T
v1.0.2
UI enhancement
v1.0.3
fhir validation server log added
IntegrityLog-Web by Ashok Kumar T
v1.0.3
Enhanced the user interface
iris-docdb-ui by Ashok Kumar T
v1.0.3
improved stability
v1.0.4
fixed minor issues
iris-embedded-python-template by Evgeny Shvarov
v3.0.7
added error log to App Log example here
v3.0.8
Error log for python even improved, thanks to Ashok Kumar T and David Hokenbroch, see the community post.
v3.0.9
More examples on Python error handling introduced by Ashok Kumar PR
iris-user-management by Evgeny Shvarov
v1.0.1
add App Log() error logging
DBsizeWatch by Robert Cemper
v0.0.2
fixed some typo
shvarov-persistent by Evgeny Shvarov
v1.1.0
Added utils.cls to enable adding ancestors to an existing class. Here is the related discussion.
Interop-LookupTable by Ashok Kumar T
v1.0.2
IPM installation option added
Most downloaded
ObjectScript-Math
By Peter Steiwer
MDX2JSON
By Eduard Lebedyuk
DeepSeeWeb
By Anton Gnibeda
zpm-registry
By Evgeny Shvarov
yaml-utils
By Benjamin De Boe
Intersystems-Monitoring
By Teunis Stolker
Test Coverage Tool
By Timothy Leavitt
WebTerminal
By Nikita Savchenko
ssl-client
By Evgeny Shvarov
December, 2025Month at a GlanceInterSystems Open Exchange
Discussion (0)1
Log in or sign up to continue
Question
· 5 hr ago

Usando /api/atelier/v1 para fazer chamadas REST SQL – Como restringir o acesso

Existe uma Master Table dentro do IRIS que estou preenchendo a partir do Epic, mas quero compartilhá-la com nossa equipe de Enterprise Application Development (Web). Como teste, consegui usar _SYSTEM a partir do Postman para executar o seguinte.

POST /api/atelier/v1/xxxx/action/query HTTP/1.1
Host: xxxxxxxx
Content-Type: application/json
Authorization: ••••••
Cookie: CSPSESSIONID-SP-443-UP-api-atelier-=00f0000000000AKyLjBfUvU$MpFD8UT8y$EoNKNw1ixZeXN4_Q; CSPWSERVERID=hzZAT5rb
Content-Length: 86

{"query": "SELECT * FROM osuwmc_Epic_Clarity.DepartmentMaster WHERE ID = '300000000'"}

Se eu criar outro usuário específico para isso, como posso restringi-lo de forma que ele possa apenas consultar tabelas específicas através da chamada REST POST?

Discussion (0)1
Log in or sign up to continue
Article
· 5 hr ago 2m read

[Dica rápida] Como criar um agente de IA usando a documentação da InterSystems no Teams

Olá a todos.

Vou dar uma dica rápida sobre como implementar um agente de IA para realizar buscas na documentação da InterSystems integrado ao Teams.

Sim, eu sei que a página da documentação tem seu próprio buscador de IA e que ele é bastante eficaz, mas dessa forma teríamos um acesso mais rápido, especialmente se o Teams for a ferramenta corporativa da sua empresa.

Também é possível criar outro agente de IA para realizar buscas nos artigos publicados na comunidade de desenvolvedores (que também possui seu buscador de IA integrado).

Passo 1

Selecione a opção "Copilot"

Passo 2

Selecione a opção "Create agent".

Se vocês não virem essa opção inicialmente, clique no botão que aparece no canto superior esquerdo.

Passo 3

Selecione a opção Configure, para não utilizar modelos já existentes.

Damos um nome ao nosso agente de IA, por exemplo, "Intersystems Docs", e uma descrição. Podemos modificar o ícone do nosso agente para torná-lo mais personalizado.

Na seção "Instructions", adicionamos as seguintes entradas:

- O agente deve buscar informações no site da InterSystems.
- Fornecer respostas precisas e relevantes com base nas informações encontradas.
- Manter um tom profissional e claro em todas as interações.
- Não fornecer informações que não estejam verificadas ou que não constem no site da InterSystems.
- Orientar o usuário para recursos adicionais, se necessário.

Adicionamos a URL da documentação da InterSystems

https://docs.intersystems.com

Nota: Se vocês quiserem criar um agente que consulte a comunidade de desenvolvedores, usem o seguinte link:

https://community.intersystems.com

Ou adicionar ambos para que a busca seja mais completa.

Passo 4

Podemos adicionar sugestões de prompts.

Title Message
Buscar informações Você pode buscar informações sobre [tema] no site da InterSystems?
Guia de recursos Você pode me guiar para os recursos disponíveis sobre [tema] no site da InterSystems?
Detalhes específicos Preciso de detalhes específicos sobre [tema] no site da InterSystems.
Últimas atualizações Quais são as últimas atualizações sobre [tema] no site da InterSystems?

Clicamos no botão "Create" e pronto… já podemos usar nosso agente de IA.

Vamos consultar qualquer coisa usando nosso novo agente; podemos fazer isso em qualquer idioma, pois ele já possui a tradução incluída.

Espero que seja muito útil para vocês, assim como foi para mim.

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