ballerina

Handling REST Client Status Code in Ballerina


I am invoking a REST service and if the status code is 404 I need to return (). Or else I need to convert it into a record type. This is the approach I followed. But in this approach, I had to invoke the REST endpoint twice. Is there a way this code can be optimised?

    http:Response response = check gitHubApiClient->/repos/[owner]/[repoName]/contents/[expression];
    if response.statusCode === http:STATUS_NOT_FOUND {
        log:printError(string `File not found in the repository ${repoName}`);
        return ();
    }
    types:RepositoryContent repoContent = check gitHubApiClient->/repos/[owner]/[repoName]/contents/[expression];

Solution

  • You can use getJsonPayload() to retrieve the payload from the initial response and then use fromJsonWithType() or cloneWithType() methods to convert the JSON payload to your user defined type.

    return (check response.getJsonPayload()).cloneWithType(types:RepositoryContent);
    

    You can refer below documentation to get a better idea,

    1 getJsonPayload

    2 convert from JSON to user-defined type