SimpleIO (SIO) examples

Making a service accept and return JSON/XML/SOAP

SIO is a declarative syntax for accepting/returning simple requests/responses. You can either return a group of attributes or a list of such groups. If hierarchies or nested structures are needed, use higher-level services to create a composite service out of SIO-based ones.

A service such as the ones below is written once, deployed and making it accept JSON/XML/SOAP is a matter of creating appropriate channels, respectively:

SIO services can create responses by reading attributes directly assigned to them, out of Python dictionaries (or any dict-like objects, such as Bunch) or from SQLAlchemy query results - hence all examples below produce the same response the data format of which (JSON/XML/SOAP) depends on what channel the service has been invoked through.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from zato.server.service import Service

class MyService(Service):
    class SimpleIO:
        input_required = ('cust_id', 'cust_type')
        output_required = ('cust_name', 'preferred_product')

    def handle(self):
        self.response.payload.cust_name = 'John Brown'
        self.response.payload.preferred_product = 'ANBZ'
1
2
3
4
5
6
7
8
9
from zato.server.service import Service

class MyService(Service):
    class SimpleIO:
        input_required = ('cust_id', 'cust_type')
        output_required = ('cust_name', 'preferred_product')

    def handle(self):
        self.response.payload = {'cust_name':'John Brown', 'preferred_product':'ANBZ'}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# bunch
from bunch import Bunch

# Zato
from zato.server.service import Service

class MyService(Service):
    class SimpleIO:
        input_required = ('cust_id', 'cust_type')
        output_required = ('cust_name', 'preferred_product')

    def handle(self):
        customer = Bunch()
        customer.cust_name = 'John Brown'
        customer.preferred_product = 'ANBZ'

        self.response.payload = customer
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# model.py

# SQLAlchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Customer(Base):
    cust_id = Column(Integer, primary_key=True)
    cust_type = Column(String(200))
    cust_name = Column(String(200))
    preferred_product = Column(String(200))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# stdlib
from contextlib import closing

# app's model
from model import Customer

# Zato
from zato.server.service import Service

class MyService(Service):
    class SimpleIO:
        input_required = ('cust_id', 'cust_type')
        output_required = ('cust_name', 'preferred_product')

    def handle(self):
        with closing(self.odb.session()) as session:
            self.response.payload = session.query(Customer).\
                filter(Customer.id==self.request.input.cust_id).\
                one()