Best way to read HTTP payload to a specific type from `http:Request` in Ballerina

42 Views Asked by At

I need to read the HTTP payload from http:Request. For that, I see multiple functions available: getJsonPayload, getXmlPayload, getTextPayload, getByteStream, getBinaryPayload.

What is the best way to identify the type and read it to a variable? Are these functions efficient, or do they just try to parse and return an error if failed? Or is the best way to check the content type and read accordingly?

I have written the following code segment, and I wonder whether we can make it more efficient?

json|xml|string? requestPayload = ();
json|http:ClientError jsonPayload = httpRequest.getJsonPayload();
if jsonPayload is http:NoContentError {
    requestPayload = ();
} else if jsonPayload is http:ClientError {
    xml|http:ClientError xmlPayload = httpRequest.getXmlPayload();
    if xmlPayload is http:ClientError {
        string|http:ClientError textPayload = httpRequest.getTextPayload();
        if textPayload is string {
            requestPayload = textPayload;
        }
    } else {
        requestPayload = xmlPayload;
    }
} else {
    requestPayload = jsonPayload;
}
1

There are 1 best solutions below

0
On

The safest approach is to read the Content-Type header first and decide on the type based on its value. This approach is used in the HTTP data binding process within the Ballerina HTTP module. The payload converter is identified by looking at the Content-Type header value.

Check the following mapping which is used in the HTTP module: HTTP Module Content Type Mapping.

Alternatively, you could use a more concise approach by taking advantage of Ballerina's type system and payload binding:

service / on new http:Listener(1234) {
   resource function post /foo (@http:Payload string|json|xml payload) {
       // if you get here, then the payload is the right type
   }
}

This way, Ballerina automatically binds the payload to the appropriate type based on the Content-Type header, making the code more readable and concise.