Set data format with WSMedia

It is important to set the correct MIME type for a Web service request or response. You can specify the data format via the WSMedia attribute.

WSMedia can contain a comma-separated list of MIME types. If you specify more than one type, the Accept header received from the client determines the payload format chosen.

Example WSMedia with record type

In this example the WSMedia attribute is set for XML to send the list of users to the client in XML format. The output is customized by WSName and XMLName attributes.

IMPORT com

TYPE profileType RECORD ... END RECORD
   
PUBLIC DEFINE myError RECORD ATTRIBUTE(WSError="My error")
  code INTEGER,
  reason STRING
END RECORD

PUBLIC FUNCTION getUsersList()
  ATTRIBUTES (WSGet, 
              WSPath="/users",
              WSDescription="Get list of users",
              WSThrows="400:Invalid,404:Not Available" )
  RETURNS (
    DYNAMIC ARRAY ATTRIBUTE(WSName="All_users_list",WSMedia="application/xml") OF profileType 
    ATTRIBUTE(XMLName="User")
    )
  
    DEFINE usersList DYNAMIC ARRAY OF profileType
    DEFINE i INTEGER
 
    WHENEVER ERROR CONTINUE
    DECLARE c1 CURSOR FOR SELECT * FROM users
    WHENEVER ERROR STOP
    CASE
      WHEN sqlca.sqlcode == 0
         INITIALIZE usersList TO NULL
         LET i=1
         FOREACH c1 INTO usersList[i].*
            LET i=i+1
         END FOREACH
         CALL usersList.deleteElement(i)
      WHEN sqlca.sqlcode == NOTFOUND
           LET myError.reason = "Nothing found"
           CALL com.WebServiceEngine.SetRestError(404,myError)
      OTHERWISE
          LET myError.reason = SFMT("SQL error:%1 [%2]",sqlca.sqlcode, SQLERRMESSAGE)
          CALL com.WebServiceEngine.SetRestError(400,myError)
     END CASE
  FREE c1
  RETURN usersList
END FUNCTION

Example WSMedia with image

For WSMedia examples using images or files, see Example: upload a file in a multipart request.