查找

公告
· 6 hr 前

Black Friday Week on Global Masters — double points & new fun journey!

Hi Community!

Black Friday is here and this year, it’s all about discovering the best deals on Global Masters! Complete a short set of fun challenges, learn a few new things and collect extra points along the way.

From November 20 to November 30, join our Black Friday adventure: Find your deal on Global Masters.

 
🎯 During this period only:

  • All asks which have a black cover will award double points during this period
  • Inviting new Developer Community members through the Referral Program will also give 2× points when the invitee registers on DC.
  • Everyone who completes the Black Friday journey will enter the raffle for a special prize - Prixton 1080P Matisse Mini Projector! 🎁

Don’t miss your chance! The Black Friday hunt ends November 30.

👉 Join the Black Friday Journey on Global Masters

Not a Global Masters member yet? Join now using your InterSystems SSO credentials (same credentials you use on DC). 
Read more about Global Masters gamification program for developers here.

讨论 (0)1
登录或注册以继续
文章
· 8 hr 前 阅读大约需 13 分钟

Introduction to Interoperability on Python (IoP) - Part2

Hi Community,

In the first part of this series, we examined the fundamentals of Interoperability on Python (IoP), specifically how it enables us to construct such interoperability elements as business services, processes, and operations using pure Python.

Now, we are ready to take things a step further. Real-world integration scenarios extend beyond simple message handoffs.They involve scheduled polling, custom message structures, decision logic, filtering, and configuration handling.In this article, we will delve into these more advanced IoP capabilities and demonstrate how to create and run a more complex interoperability flow using only Python.

To make it practical, we will build a comprehensive example: The Reddit Post Analyzer Production. The concept is straightforward: continuously retrieving the latest submissions from a chosen subreddit, filtering them based on popularity, adding extra tags to them, and sending them off for storage or further analysis.

The ultimate goal here is a reliable, self-running data ingestion pipeline. All major parts (the Business Service, Business Process, and Business Operation) are implemented in Python, showcasing how to use IoP as a Python-first integration methodology.

We will cover the following topics in this article:

✅ Defining message models using @dataclass
✅ Pulling live data from Reddit (Business Service)
✅ Filtering and enriching posts (Business Process)
✅ Handling the final delivery (Business Operation)
✅ Using structured logging across the pipeline
✅ Migrating IOP classes into IRIS using settings.py
✅ Overview of the IOP Director utility class


Let's begin with the application folder structure:

reddit_iop/
 ├─ messages.py
 ├─ services/
    └─ service_reddit.py
 ├─ processes/
    └─ process_reddit.py
 ├─ operations/
    └─ operation_store.py
 ├─ settings.py    
    

✅ Defining Message Models Using @dataclass (messages.py)

A central concept in any integration framework is the Message.In InterSystems IRIS, messages are first-class objects (they can be traced, inspected, and persisted as they move through production). One of the strengths of IoP is that we can define these messages as typed Python classes using @dataclass. It means that we can avoid creating ObjectScript message classes and instead benefit from clean, IDE-friendly Python models.

In IoP, Message is the base class for anything passed between components. We will build upon it to create our own strongly-typed message objects with the help of Python dataclasses. These data models will flow through the Business Service, Business Process, and Business Operation.

from iop import Message
from dataclasses import dataclass

@dataclass
class RedditPostMessage(Message):
    Title: str = ""
    URL: str = ""
    Author: str = ""
    Score: int = 0
    Tag: str = ""
    Status: str = ""

By using the @dataclass decorator on a class that inherits from iop.Message, we achieve several advanced benefits with minimal code:

  • Automatic Properties: dataclasses automatically generates the __init__, __repr__, and comparison methods based on the type-hinted fields (Title: str, Score: int, etc.).
  • Strong Typing: Type hints ensure that all components are aware of the expected data type, which improves code quality and prevents runtime errors.
  • IoP Integration: The iop.Message inheritance ensures that the Python class is compiled into a persistent, ObjectScript-compatible class within InterSystems IRIS. It means that every message sent is automatically saved in the database for auditing and visual tracing (a key feature of the IRIS platform).

✅ Pulling Live Data from Reddit (service_reddit.py)

In an interoperability production, the Business Service acts as the gateway that brings data into the system. For our demonstration, the service will continuously poll Reddit’s /new.json endpoint and feed new submissions into the processing pipeline.

This component uses an inbound adapter to schedule and execute periodic API calls. Each time the adapter runs, it requests the latest posts from the specified subreddit, wraps the relevant fields in our RedditPostMessage dataclass, and forwards it to the next stage in the flow.

Key responsibilities of this service include:

  • Initiating the data flow at defined intervals
  • Connecting to Reddit and retrieving the newest submissions
  • Converting raw API response data into a strongly-typed RedditPostMessage
  • Logging errors cleanly without interrupting the production
  • Forwarding well-structured messages to the Business Process layer

This configuration mirrors a real-world integration pattern where an external data source continuously feeds the integration engine. By combining the IoP inbound adapter with a Python-based message model, we achieve a reliable and traceable ingest layer that is independent of ObjectScript.

from iop import BusinessService
from messages import RedditPostMessage
import requests, time

class RedditService(BusinessService):
    #Required to schedule service
    def get_adapter_type():
        # This is mandatory to schedule the service
        # By default, the service will be scheduled every 5 seconds
        return "Ens.InboundAdapter"
    #Initializes loop settings
    def on_init(self):
        self.subreddit =  "technology"
        self.poll_interval = 10
        self.base_url = f"https://www.reddit.com/r/{self.subreddit}/new.json?limit=5"
        self.headers = {"User-Agent": "IRIS-IoP-Reddit-Agent"}
    
    #Infinite polling loop to fetch events
    def on_process_input(self, _):
        while True:
            try:
                response = requests.get(self.base_url, headers=self.headers)
                posts = response.json()["data"]["children"]
                
                for post in posts:
                    data = post["data"]

                    msg = RedditPostMessage(
                        Title=data["title"],
                        URL="https://reddit.com" + data["permalink"],
                        Author=data["author"],
                        Score=data["score"]
                    )
                    #Sends message to Process component
                    self.send_request_sync("RedditProcess", msg)

                self.log_info(f"[RedditService] Pulled {len(posts)} posts")

            except Exception as e:
                self.log_error(f"[RedditService ERROR] {e}")

            time.sleep(self.poll_interval)

✅ Filtering and Enriching Posts (process_reddit.py)

The Business Process acts as the central nervous system of the production. This is where raw Reddit submissions are converted into meaningful information, and such key business rules as filtering, decision-making, and routing are executed.

Once the Business Service publishes a RedditPostMessage,  the process assesses its contents and determines the next course of action.

In this example, the process checks whether the submission meets specific criteria (e.g., a minimum score or specific keywords).Posts that pass the filter are augmented and forwarded toward our Business Operation, while those that don’t are logged and dropped to keep the workflow clean and efficient.

from iop import BusinessProcess
from messages import RedditPostMessage

class RedditProcess(BusinessProcess):
    def on_init(self):
        self.log_info("Hello World init")
    #Entry point for incoming messages.
    def on_request(self, request: RedditPostMessage) -> RedditPostMessage:
        title = request.Title
        score = request.Score

        self.log_info(f"[Process] Received: {title} | Score: {score}")

        # Filter logic: process only trending posts
        min_score = 5
        if score < min_score:
            self.log_info(f"[Process] Skipped low score ({score}) post")
            response = RedditPostMessage(Status="FilteredLowScore")
            return response

        # Enrichment
        request.Tag = self._tag_topic(title)

        self.log_info(f"[Process] Tagged topic: {request.Tag}")

        # Forward to operation
        return self.send_request_sync("RedditStoreOperation", request)
    
    #Detects topic from keywords
    def _tag_topic(self, title: str) -> str:
        keywords = {
            "AI": "Artificial Intelligence",
            "health": "Healthcare",
            "python": "Programming",
            "data": "Data Engineering",
        }
        for key, tag in keywords.items():
            if key.lower() in title.lower():
                return tag
        return "General"
  • Filtering and Early Exit: The if score < min_score: block demonstrates conditional processing. If the message does not meet the requirements (low score), the process logs the skip and returns a simple StatusResponse, terminating that message's journey early without sending it downstream.
  • Data Enrichment: The line request.Tag = self._tag_topic(title) shows how to modify the message object (which is a Python object in memory). The _tag_topic function performs simple business logic (categorization) and adds the result to the message, making the data more valuable for the storage component.
  • Internal Methods: Python enables clean object-oriented design, as demonstrated by _tag_topic. This function, encapsulated within the class, keeps the main on_request method clean and focused on orchestration.
  • Continuing the Pipeline: If the post passes the filter, the augmented message is passed to the Operation using self.send_request_sync(), ensuring the flow remains synchronous for full traceability in the visual message tracer.

✅ Handling the Final Delivery (operation_store.py)

The Business Operation is the final component in the production pipeline that interacts with external systems. This could be a database, a file system, a remote API, a message queue, or any other destination for processed data.

Once a message reaches this layer, it is considered fully processed and ready for persistence, storage, or further consumption. In our demonstration, the operation logs the post details and simulates saving them. Still, in a real-world scenario, this is where you would execute SQL inserts, REST calls, or send messages to other systems.

from iop import BusinessOperation
from dataclasses import dataclass
from messages import RedditPostMessage


class RedditStoreOperation(BusinessOperation):
    def on_init(self):
        self.log_info("Operation init")
        
    #standard entry point for operations.    
    def on_message(self, request: RedditPostMessage) -> RedditPostMessage:
        self.log_info(
            f"[Store] Title: {request.Title} | Score: {request.Score} | Tag: {request.Tag}"
        )
        # Mock DB or File writing here
        # Real system: SQL insert / Kafka / FHIR server POST
        # Simulates saving to a database, file, or external system.
        response = RedditPostMessage(Status="Saved")
        #returning the status to close the loop
        return response
  • Input Handling: The method signature on_message(self, request: RedditPostMessage) clearly defines the expected input type, reinforcing the contract set by the custom message.
  • External Integration Point: This is the most crucial architectural point. All Python packages, including requests, numpy, pandas, and such specialized connectors as pyodbc or boto3, are available here. The developer is free to use the entire Python ecosystem to interact with any external system.
  • Returning Status: The operation successfully executes its task (mocked as logging) and returns a StatusResponse to the calling Process. Since the Service called the Process synchronously, this final status can be traced all the way back to the Service's on_process_input method, confirming the end-to-end completion.

✅ Using Structured Logging Across the Pipeline

The IoP framework includes its own logging system, and the Python API provides a way to leverage Python’s logging capabilities while fully integrating with IRIS logs.

Every IoP component inherits the logging functionality from its base class. You can access it directly via the logger property or use the built-in convenience methods, such as log_info(), log_warn(), and log_error(), to record messages at the appropriate level.

def on_init(self):
    # Using convenience methods
    self.log_info("Component initialized")
    self.log_error("An error occurred")
    self.log_warning("Warning message")
    self.log_alert("Critical alert")
    self.trace("Debug trace message")

    # Using logger property
    self.logger.info("Info via logger")
    self.logger.error("Error via logger")

✅ Migrating IOP Classes into IRIS Usingsettings.py

This is the “glue” that links your Python classes to production items in IRIS. The IoP framework utilizes the settings.py file to define and apply configuration details, which are then reflected directly in the InterSystems Management Portal.

from services.service_reddit import RedditService
from processes.process_reddit import RedditProcess
from operations.operation_store import RedditStoreOperation

CLASSES = {
    "Reddit.Ingestion.Service": RedditService,
    "Reddit.Ingestion.Process": RedditProcess,
    "Reddit.Ingestion.Store": RedditStoreOperation
}

PRODUCTIONS = [
    {
        "Reddit.Ingestion.Production": {
            "@TestingEnabled": "false",
            "Item": [
                {
                    "@Name": "RedditService",
                    "@ClassName": "Reddit.Ingestion.Service",
                    "@Enabled": "true",
                       "Setting": [
                    {
                        "@Target": "Host",
                        "@Name": "subreddit",
                        "#text": "technology"
                    },
                      {
                        "@Target": "Host",
                        "@Name": "poll_interval",
                        "#text": "15"
                    },
                ]                
                },
                {
                    "@Name": "RedditProcess",
                    "@ClassName": "Reddit.Ingestion.Process",
                    "@Enabled": "true",
                         "Setting": [
                    {
                        "@Target": "Host",
                        "@Name": "MIN_SCORE",
                        "#text": "200"
                    }
                ]          
                },
                {
                    "@Name": "RedditStoreOperation",
                    "@ClassName": "Reddit.Ingestion.Store",
                    "@Enabled": "true"
                }
            ]
        }
    }
]
  • Dynamic Setting Injection: The Setting array within the PRODUCTIONS definition is the mechanism for externalizing configuration. When the production is loaded, IRIS reads these values and makes them available to the Python components via the self.get_setting() method or the self.Settings property.
  • Live Configuration Change: A significant advantage of using this framework is that administrators can modify the SUBREDDIT, POLL_INTERVAL, or MIN_SCORE directly in the InterSystems IRIS Management Portal without needing to restart the production. The on_init method will be triggered to re-read these settings, enabling dynamic operational control.
  • Clear Structure: The CLASSES dictionary acts as a mapping layer, simplifying the connection between the ObjectScript-facing Production XML (@ClassName) and the underlying Python implementation. This abstraction is vital for large, multi-language projects.

Using the iop command, we can migrate our Python components directly into IRIS, making them available as production items in the InterSystems environment.

iop --migrate /path/to/reddit_iop/settings.py

✅ Overview of the IOP Director Utility Class

The IOP Director class provides utility methods to manage productions and components in IRIS directly from Python.

Production Management:

  • start_production(production_name=None) – Starts a production 
  • stop_production() – Stops the current production
  • restart_production() – Restarts the current production
  • shutdown_production() – Gracefully shuts down the production
  • status_production() – Gets current production status (returns a dictionary)

Business Service Management:

  • create_business_service(target) – Creates a new service instance
  • get_business_service(target) – Retrieves an existing service instance
  • test_component(target, message=None, classname=None, body=None) – Tests any production component

Production Logging:

  • log_production() – Monitors logs in real time
  • log_production_top(top) – Displays the last N log entries

Production Configuration:

  • set_default_production(production_name) – Sets the default production
  • get_default_production() – Gets the current default production name

The Director class makes it easy to control, monitor, and test your IoP productions without leaving the Python environment.

To initiate a production, you can use the start_production() method of the Director class.




Production Overview

The following production has been created with the help of the iop --migrate command:

Below you can see the business service details (%classname refers to the class name in our service_reddit.py file, %module with the help of the Python file name, and %classpaths contains the path to the Python file)


To view the messages, click on the Business Service, then navigate to the Message tab.


Click on a message to view its visual trace.

Messages are received by RedditService, forwarded to RedditProcess, and then, based on the process logic, sent to RedditStoreOperation.

Conclusion

With Interoperability on Python, you can now do the following:

  • Build complete production pipelines entirely in Python
  • Leverage such modern tooling as dataclasses, type hints, and IDE support.
  • Integrate with virtually any API (Reddit, Twitter, FHIR, and more)
  • Deploy Python components alongside ObjectScript components

It provides a solid foundation for creating real-time data pipelines in such domains as healthcare, finance, IoT, and social media (all powered by Python within InterSystems IRIS).

The Reddit Post Analyzer Production serves as a blueprint for advanced IoP development. By utilizing custom dataclass messages, implementing robust polling services, applying conditional logic and enrichment within the Business Process, and externalizing configuration through settings.py, we have revealed how Python can evolve from a utility language into a core pillar of a high-performance enterprise integration platform.

Thanks!

2 条新评论
讨论 (2)1
登录或注册以继续
文章
· 9 hr 前 阅读大约需 8 分钟

Revolutionizing Healthcare: The Impact of Electronic Medical Records (EMR) on Patient Care

Quick Summary

EMR is revolutionizing the healthcare sector by enhancing quality care given to patients, increasing the accuracy of the data, and improving clinical processes. EMR systems allow medical staff to retrieve the whole patient history, lab tests, and treatment plans in real time and prevents the occurrence of errors and delays. EMRs increase efficiency, coordination, and patient safety by including safe data storage, automatic alerts, and decision-support tools. In general, EMRs transform the healthcare sector making it smarter, faster, and more informed.

Introduction

The healthcare sector is developing rapidly, and the EMR program has become one of the pillars of enhancing patient care and efficiency at work. Emr systems enable healthcare providers to retrieve correct medical histories, lab results, and treatment plans in real time by digitizing patient records and reducing the number of errors and improving decision-making.

Selecting an optimal EMR software is paramount to the healthcare organizations that would like to automate their workflows and enhance patient outcomes. The Modern Electronic Medical Records Software incorporates such functionality as automated alerts, prescription control, and data storage, and guarantees efficiency and adherence to healthcare regulations.

The integration of EMR Software in India is on a gradual but increasing trend in India due to the presence of hospitals and clinics that would like to have a reliable EMR Software Solutions. The use of a strong EMR Software Solution will enable medical facilities to keep precise records and improve the cooperation of healthcare teams, as well as provide safer and more efficient care to patients, which is why EMRs have become an indispensable part of healthcare nowadays.

Knowing Electronic Medical Records (EMR)

EMR system hospital is a hospital that uses digitized records to handle the data about patients effectively. However, what exactly is EMR software? It is an online product that stores, organizes and manages patient medical histories, lab results, prescriptions, and treatment plans in a secure and accessible format.

The top emr software vendors create solutions to simplify clinical processes, minimize errors and improve patient care. The use of modern Electronic Medical Records Software enables real-time access to information, the ability to communicate with colleagues on a team in healthcare, and the enhanced adherence to medical regulations.

EMR Software Solutions In India, the demand of EMR Software in India is increasing as hospitals and clinics resort to the use of advanced EMR Software Solutions to enhance efficiency in operations and data security. The use of an effective EMR Software does not only guarantee proper documentation of records but also facilitates effective decision-making, improved patient outcomes, and a more interconnected healthcare ecosystem.

The History of EMR in the Healthcare industry

The adoption of EMR Software in the healthcare sector has brought about a major shift in the sector. Firstly, records of patients were kept manually hence creating inefficiencies and errors. With the implementation of Electronic Medical Records Software, a digital option was introduced, and now hospitals and clinics can store, retrieve, and manipulate patient information safely.

A modern emr system hospital offers access to clinical decision-making and patient care by delivering medical histories, lab outcomes, and prescriptions in real time. Knowing what is emr software assists healthcare providers to choose the appropriate tools according to their requirements.

The market leaders of emr software provide superior EMR Software Solutions, which also incorporate billing, scheduling, and reporting capabilities. EMR Software in India is gaining popularity in India to streamline processes, increase the level of data security, and assist in compliance with the regulations. The contemporary EMR Software guarantees an effective functioning and improved healthcare functions.

Important Patient Care EMR Advantages

The benefits of implementing EMR Software are many and directly relate to providing better care to a patient. Emr systems enable healthcare providers to make timely decisions in a matter of seconds with complete access to a history of medical care, thus eliminating error and enhancing treatment effectiveness.

The most effective EMR software can be combined with such capabilities as prescription ordering, monitoring lab results, and alerts to be sure that patients are properly and timely taken care of. Electronic Medical Records Software also facilitates the improved coordination of the healthcare teams allowing the smooth communication and collaboration across the departments.

The implementation of EMR Software in India would assist in streamlining the processes at hospitals and clinics in India, and ensuring that the healthcare facilities remain compliant with healthcare standards. A strong EMR Software Solution can improve the security of data, decrease administration load and patient satisfaction. Altogether, EMRs enable providers to provide safer, more efficient, and quality healthcare services.

EMR and Patient Safety

In the contemporary healthcare setting, patient safety is a priority, and EMR Software is relevant in reducing the number of mistakes and enhancing outcomes. Through the provision of precise and current information, emr systems aid healthcare providers to prevent errors in prescription, redundancy, and misdiagnoses.

The ideal EMR software has the capacity to provide automated alerts, drug interactions, and real-time patient history and provides safer clinical decisions. The Electronic Medical Records Software is also a solution that allows tracking the progress of patients and identifying possible complications in early stages.

In India, patient safety in India is being improved on the adoption of EMR Software in India, as it is standardizing its records and assisting in the compliance of regulation. A well-trusted EMR Software Solution enhances the safety of data, fosters responsibility, and facilitates the ability of the healthcare teams to deliver prompt, knowledgeable, and secure care, which ultimately can result in better patient outcomes.

The problems of EMR Implementation

There are various obstacles that are encountered even as an EMR system is implemented within a hospital. One of the biggest obstacles is the concept of knowing what emr software is and choosing the appropriate product that will suit the working process and regulations of the hospital. It is difficult to settle on a single product in the market of various emr software vendors, and the selection process is a complicated time-consuming task.

Implementation of the Electronic Medical Records Software would involve much staff training to use the software appropriately to prevent interruption of the hospital work temporarily. The transformation of paper records into digital records may be a tedious task that is also subject to error.

In India, the adoption of EMR Software in India is also concerned with the limitation of infrastructure and reliability of network and adherence to local regulation. To cope with these issues and guarantee the success of an EMR Software Solution implementation, a robust computer program must possess technical support, user-friendly interfaces, and scalable features.

EMR Adoption Best Practices

ERM implementation is a process that needs to be planned and executed properly. The first step would be to choose the most appropriate EMR software, which must meet the needs of the organization and improve clinical workflows. The knowledge of emr software and what it is able to do can allow healthcare providers to make better decisions and take full advantage of the benefits offered by the system.

The process of staff training is also important in the implementation of emr systems in order to assign the proper use of the same and to reduce the errors. Frequent upgrades, customer service and performance overview allow keeping the efficiency and reliability. EMR software must have the ability to work with already offered hospital systems such as billing, scheduling, and lab administration.

In India, selecting a powerful EMR Software in India with powerful EMR Software Solutions will make sure the regulations in the country are met and enhance security of data. Adherence to these best practices can help healthcare facilities to provide better patient care, operational streamlining, and successful EMR adoption.

Trends and Innovations in Healthcare EMR

The healthcare sector is changing very fast, and the EMR Software remains a source of innovation. Emr systems are modern, cloud-based, mobile and powered with AI and improve patient care and operational effectiveness. It is better to understand what is emr software to enable the healthcare providers to utilize such advanced features.

The major emr software providers are creating Electronic Medical Records Software that combines telemedicine, analytics, and automated workflows and minimizes care errors and enhances care coordination. With emr system hospital, hospitals are now able to gain access of real-time patient data within the departments, facilitating the diagnosis and treatment process.

EMR Software in India gains traction, and the solutions are designed regarding local regulations and healthcare requirements. An effective EMR Software Solution in place guarantees safe data management, scalability, and compliance enabling the hospital and clinics to adapt to future advancements and care about patients in high quality.

Effects of EMR on Healthcare Productivity

The adoption of EMR Software helps to streamline the working process in healthcare facilities to a great extent, and it minimizes the administrative load. Emr systems enable medical practitioners to have access to patient records, laboratory findings, and treatment history on real-time basis thereby reducing delays and mistakes.

The most appropriate EMR software will combine such functions as appointment booking, billing, and prescription management, automating regular operations and releasing staff for working with patients. EMRS Software also facilitates interdepartmental coordination, which means that communication is seamless and has quicker decision-making.

Adoption of EMR Software in India is assisting hospitals and clinics in streamlining the operations and ensuring that they do not violate the regulations. An efficient EMR Software Solution helps in ensuring safe data storage, audit trails, and analytics, which will assist the healthcare providers to track their performance and enhance resource utilization. Comprehensively, EMRs improve the effectiveness of operations, lower expenses, and provide improved patient outcomes.

Conclusion

EMRs have revamped the healthcare sector by enhancing patient care, safety, and efficiency in the working process. The use of trusted EMR Software and emr systems will help access patient information in real-time, minimize inaccuracies, and simplify the clinical processes. The most effective EMR software has the ability to combine such functions as billing and planning and analytics, and assists in making improved decisions and coordinating the actions of healthcare teams. EMR Software in India and comprehensive EMR Software Solutions are used in India to assist hospitals and clinics with their adherence to their regulations as well as to improve the data security. On the whole, EMRs are the critical tools that enable healthcare professionals to provide efficient, safe, and high-quality care to patients in the digital age.

讨论 (0)1
登录或注册以继续
文章
· 9 hr 前 阅读大约需 4 分钟

Consumiendo API REST para principiantes (apto para novatos)

Como desarrollador que usa IRIS como base de datos en un par de proyectos, uso APIs REST todo el tiempo. En mi opinión, saber cómo consumir un recurso de una API REST es crucial para poder utilizar APIs REST externas con %Net.HttpRequest, porque permite la integración con aplicaciones y servicios web modernos, y es una habilidad esencial para un desarrollador backend que ama y utiliza IRIS como base de datos.

¿Qué es y para quién sirve %Net.HttpRequest?

Es solo una clase, pero es la forma adecuada de hacer solicitudes fuera del framework. Es una clase sencilla que proporciona métodos HTTP como GET, POST y PUT, además de otros métodos de solicitud, os permite “jugar” con los encabezados, crear la solicitud como queráis y gestionar la respuesta que recibáis. Por cada solicitud enviada usando %Net.HttpRequest, recibimos un objeto %Net.HttpResponse que contiene la respuesta con el mismo patrón.

Una forma adecuada de manejar solicitudes a APIs REST con %Net implica comprobar tanto el valor devuelto por %Status como los códigos de estado de la respuesta, lo cual os permite generar mensajes de error específicos y filtrar las respuestas cuando la solicitud falla. La forma recomendada es usar macros como $$$ISER() o $SYSTEM.Status.IsOK(). También podemos usar $SYSTEM.Status.DisplayError() para inspeccionar el código de estado HTTP y gestionarlo.

Antes de empezar a ensuciarnos las manos, debemos saber quién es JSONPlaceholder, así que en el sitio oficial dicen:

"API falsa, gratuita y fiable para pruebas y prototipos"

Y eso es exactamente lo que es: una API REST gratuita en línea para experimentar. Son datos falsos, incluso podemos enviar datos con POST, pero esta guía trata únicamente de consumir datos, así que centrémonos en eso. Y este es un ejemplo sencillo de cómo consumir un JSON desde un servicio REST API.

Set request = ##class(%Net.HttpRequest).%New()
Set request.Server = "jsonplaceholder.typicode.com"
Set status = request.Get("/posts/1")

If $$$ISERR(status) {
    Do $SYSTEM.Status.DisplayError(status)
    Quit
}

Set response = request.HttpResponse
Set httpStatus = response.StatusCode
Set body = response.Data.Read()

If httpStatus < 200 || httpStatus >= 300 {
    Write "HTTP Error: ", response.StatusLine, !
    Quit
}

Write "HTTP Status: ", response.StatusLine, !
// Do what ever you want with it!

¿Qué hacemos?

  1. Asignar “request” a una nueva instancia del objeto %New.HttpRequest.
  2. Asignar una ubicación/dirección a la propiedad Server en la instancia de request.
  3. Hacer una solicitud GET al endpoint que proporcionamos a la función “/posts/1”, lo que significa que pedimos datos de “posts” con id igual a 1 (para obtener solo el primer mensaje; podemos especificar solo “posts” y obtenerlos todos; es bueno trastear con ello).
  4. Comprobar si hay algún error en la función usando $$$ISERR con el estado devuelto por el método GET de la solicitud. Si no lo hay, la solicitud se envió correctamente desde nuestro endpoint.
  5. Asignar la variable response desde el propio objeto request.
  6. Extraer el código de estado y el cuerpo.
  7. Comprobar si el código de respuesta es OK. Si el código devuelto es mayor que 200 y menor o igual que 300, está OK (307 es una redirección, así que no es lo que necesitamos aquí).

Entonces, en perspectiva general, ¿qué estamos haciendo aquí?

  1. Crear una solicitud predefinida usando la clase
  2. Intentar consumir los datos que necesitamos
  3. Gestionar los casos tanto de error como de éxito

Si todo va bien, deberíais obtener algo así como un objeto JSON:

Y así es como consumimos datos de una API REST, pero ¿qué podemos hacer con ello?
Veamos cómo extraer los datos de la respuesta:

Set reponseBodyAsJSON = {}.%FromJSON(body)

Write "id: ", reponseBodyAsJSON.id, !
Write "title: ", reponseBodyAsJSON.title, !
Write "body: ", reponseBodyAsJSON.body, !

De esta manera, dividimos la respuesta en pares clave-valor como debe ser un JSON.
Así es como podemos acceder y consumir fácilmente un recurso de una API REST usando el método GET y la clase %Net.HttpRequest. Esta es una guía realmente apta para principiantes que os permite tener una “visión general” de cómo lo hacemos.

Aprender la magia de las APIs REST es vuestro deber.

Como este tema es muy accesible, podéis experimentar fácilmente haciendo solicitudes y probando diferentes métodos. En la próxima guía veremos cómo transferir datos de forma segura entre dos servicios basados en REST.

讨论 (0)1
登录或注册以继续
InterSystems 官方
· 12 hr 前

InterSystems IRIS, InterSystems IRIS for Health, HealthShare Health Connect 2025.3 のリリースのご案内

インターシステムズは InterSystems IRIS®InterSystems IRIS® for HealthTMHealthShare® Health Connect のバージョン 2025.3 をリリースしました。
2025.3 は Continuous Delivery(CD)リリースです。
 

【リリースハイライト】
Secure Wallet(セキュアウォレット)
  IRISSECURITY データベース上に構築された、新しい暗号化フレームワークで、機密データ管理を強化し、システムのセキュリティとアクセス制御を向上しました。

拡張されたオブザーバビリティとクラウド連携
  OpenTelemetry メトリクスが強化され、新たにプロセスおよび ECP メトリクスを追加しました。さらに、ジャーナルアーカイブが Azure Blob Storage に対応し、コスト効率の高い保管が可能になりました。

データ & AI の改善
  外部テーブルで JOIN のプッシュダウンがサポートされ、SQL パフォーマンスが向上しました。ベクトル検索では高速かつ堅牢な類似検索を実現する改良版 HNSW インデックスを導入しました。

ヘルスケア機能の強化
  FHIR Bulk Data Access と認証機能が改善されました。

開発者 & UI のアップデート
  Interoperability UI に一括管理アクションや、プロダクション構成内での拡張検索機能が追加され、大規模プロダクションでも使いやすいユーザビリティを実現し、モダンなユーザー体験をさらに強化します。

より良い製品を一緒に作り上げていくために、これらの機能強化に対するフィードックを開発者コミュニティで共有してください。
 

【ドキュメント】
注目の機能についての詳細は、以下のリンクからご覧いただけます (すべて英語) :

・InterSystems IRIS 2025.3 ドキュメントリリースノート

・InterSystems IRIS for Health 2025.3 ドキュメントリリースノート

・Health Connect 2025.3 ドキュメントリリースノート

さらに、アップグレードの影響に関するチェックリストでは、このリリースにアップグレードする際に注意する必要があるすべての変更点の概要を簡単に確認できます。
 

【早期アクセス・プログラム (EAP)】
現在、多くの EAP が用意されています。このページより興味のあるものに登録してください。こちらから登録できます
 

【ソフトウェアの入手方法】
通常通り、Continuous Delivery (CD) リリースには、サポートされているすべてのプラットフォーム用のクラシックインストールパッケージと Dockerコンテナ形式のコンテナイメージが付属しています。
 

【クラシックインストールパッケージ】
インストールパッケージは、InterSystems IRIS および InterSystems IRIS for Health 用は WRC の InterSystems IRIS のページから、Health Connect 用は HealthShare  のページから入手できます。さらに、キットは評価サービスのウェブサイトにもあります。
 

【Availability と Package の情報】
このリリースには、サポートされているすべてのプラットフォーム用のクラシック・
インストール・パッケージと Docker コンテナ形式のコンテナ・イメージが付属して
います。 一覧については サポート対象プラットフォーム をご参照ください。

この Continuous Delivery のビルド番号は次のとおりです : 2025.3.0.226.0

このリリースには、InterSystems Container Registry から入手可能な Dockerコンテナ形式のコンテナ・イメージが付属しています。IRIS コンテナには "2025.3""latest-cd" の両方のタグが付けられています。

讨论 (0)0
登录或注册以继续