Discussion
· 7 hr ago

What is the best way to output JSON data in a REST API GET request?

Hi devs!

What is the best way to return JSON in IRIS for a GET request in a REST app?

This is how I do it now:

ClassMethod GetAllPersons() As %Stream.Object
{
    d ..%SetContentType("application/json")
    Set rset = ##class(dc.Sample.Person).ExtentFunc()

    set stream=##class(%Stream.TmpCharacter).%New()
    d stream.Write("[")
    if rset.%Next() {
        Set person = ##class(dc.Sample.Person).%OpenId(rset.ID)
        Do person.%JSONExportToStream(.stream)
    }
    While rset.%Next() {
        d stream.Write(",")
        Set person = ##class(dc.Sample.Person).%OpenId(rset.ID)
        Do person.%JSONExportToStream(.stream)
    }
    d stream.Write("]")
    return stream
}

What I don't like:

1. "Unnecessary" "manual" writes of "[]":

d stream.Write("[")

2. Code block repeat for the first segment to excuse "," :


    if rset.%Next() {
        Set person = ##class(dc.Sample.Person).%OpenId(rset.ID)
        Do person.%JSONExportToStream(.stream)
    }
    While rset.%Next() {
        d stream.Write(",")
        Set person = ##class(dc.Sample.Person).%OpenId(rset.ID)
        Do person.%JSONExportToStream(.stream)
    }

3. I should introduce an "artificial" PersonId to make the response include record ID's (thanks to @Robert Cemper):

Property PersonId As %Integer [ Calculated, SqlComputeCode = { set {*}={%%ID}}, SqlComputed ];

Your ideas?

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

Hello @Evgeny Shvarov 
I directly use %DymaicObject and %DynamicArray and its methods depends on the response type (array or object) to set the values into the JSON response and I use %WriteResponse to write that response to the API call

 Class sample.Impl Extends  %REST.Impl {
 
 ClassMethod GetAllPersons() As %Stream.Object
{
    d ..%SetContentType("application/json")
    set res =  {"name":"test" 
    do ..%SetStatusCode(200)
    do ..%WriteResponse(res)
    q 1
    
}

Mixed of stream data types and other datas then creates a stream and convert into DynamicObject if required and write that response.