Set a request body as optional

If the input body parameter is specified with the WSOptional attribute, functions that update a resource have the option of not getting a request body.

It is typical to specify an input body parameter when performing an HTTP PUT, POST, or PATCH request to a resource; otherwise error-9106 is raised.

You can set WSOptional on the ATTRIBUTES() clause of an input body parameter if a body is not always required. When set as optional, the fglrestful tool generates two Genero BDL functions for the same service in the stub file:
  • the standard function, where you provide the input body parameter.
  • a second function, suffixed with "NoRequestBody", where there is no input body parameter. For example:
    PUBLIC FUNCTION TestRecord NoRequestBody() RETURNING (INTEGER, INTEGER)
As a result, the service is able to handle all client requests, with or without an input body.
Important:

If you have multipart input bodies and any one input body is optional, then all input parameters must set the WSOptional attribute; otherwise fglcomp will raise error-9138.

Example: Optional input body

In this sample REST function the user-defined WSContext variable is used to check if the request body exists. The WSOptional attribute is set on the parameter (rec) for input sent in the request body.

You must code in the function to have WSContext detect whether the client has sent a body at runtime. If the request does not have an input body parameter, the GWS sets the "NoRequestBody" entry in the WSContext variable to true.

The function needs to receive data of the required structure in either a JSON or XML representation.

PRIVATE DEFINE Context DICTIONARY ATTRIBUTES(WSContext) OF STRING

PUBLIC
FUNCTION testRecord(rec RECORD ATTRIBUTES(WSOptional) a INTEGER, b INTEGER END RECORD)
  ATTRIBUTES (WSPut, 
             WSPath = "/record",
             WSDescription = "Check for request body with WSContext variable")
  RETURNS (INTEGER)
  IF Context.contains("NoRequestBody") THEN
    DISPLAY Context["NoRequestBody"]
    RETURN 0
  ELSE
     RETURN rec.a + rec.b
  END IF
END FUNCTION