Set a request body
Functions that create or update a resource need to set a request body for the incoming payload. You specify the request body in an input parameter.
Typically, you specify an input body parameter when you
perform an HTTP PUT, POST, or PATCH request to a resource, otherwise you get error-9106. However, you
can set WSOptional
on the ATTRIBUTES()
. For a sample function, see Set a request body as optional.
In your BDL function, you specify a request body by declaring an input parameter that does not
have any WSHeader
, WSQuery
, WSCookie
, or
WSParam
attributes.
If you have more than one of such input parameters, it means your payload is delivered in a multipart body request.
Example specifying a request body
In this sample REST function a user record is updated with a value sent in the request body. The
function's id
parameter specifies the user to update. The
lname parameter of type STRING
provides the user
details to update.
If the data type is not a primitive data type, you may need to define a type suitable for the structure in your module. The function needs to receive data of the required structure in either a JSON or XML representation. For an example, see Example: create resource with WSPost.
WSThrows is set to handle errors. In the TRY/CATCH
block, the sqlca
record is checked after
the execution of the SQL query. The SQLERRMESSAGE
is set to the
message
field of the userError
variable, and a call to
SetRestError()
returns the message defined in WSThrows
for the error.
IMPORT com
PUBLIC DEFINE userError RECORD ATTRIBUTES(WSError = "User error")
message STRING
END RECORD
PUBLIC FUNCTION updateUsersField(
id INTEGER ATTRIBUTES(WSParam, WSDescription = "User id"),
lname STRING ATTRIBUTES(WSDescription = "User's last name"))
ATTRIBUTES(WSPut,
WSPath = "/users/{id}",
WSDescription = "Update name of a given user",
WSThrows = "400:@userError")
RETURNS STRING
DEFINE ret STRING
TRY
UPDATE users
SET name = lname WHERE @id = id
IF sqlca.sqlerrd[3] = 1 THEN # sqlerrd[3] = processed rows
LET ret = SFMT("Updated user with ID: %1",id)
ELSE
LET ret = SFMT("No user with ID: %1",id)
END IF
CATCH
LET ret = SFMT("Error updating user with ID: %1",id)
LET userError.message = SFMT("SQL error:%1 [%2]",
sqlca.sqlcode, SQLERRMESSAGE)
CALL com.WebServiceEngine.SetRestError(400,userError)
END TRY
RETURN ret
END FUNCTION
