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.
For records and arrays in the message response the default MIME type can be JSON
(application/json
) or XML (application/xml
).
WSMedia
can
contain a comma-separated list of MIME types. The payload format is chosen according to that
specified in the Accept header received from the client using the Web service.
In the 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.
Example WSMedia with record type
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:NotAvailable" )
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.