httpballerinaballerina-http

How to Add a Custom Field to an HTTP Return Record Type in Ballerina


I want to add a custom id field as part of the HTTP body. Here is my code that works, But this is not type-safe, since id is open to anydata and easy to make mistakes.

import ballerina/http;

service on new http:Listener(9090) {

    resource function get hello() returns http:Created {
        http:Created res = {body : { id : "123"}};;
        return res;
    }
}

Solution

  • In order to make this type safe, I have to define a new record type, which represents the id field.

    import ballerina/http;
    
    public type Created record {|
        *http:Created;
        record {|
            string id;
        |} body;
    |};
    
    service on new http:Listener(9090) {
    
        resource function get hello() returns Created {
            Created res = {body: {id: "123"}};
            return res;
        }
    }
    

    By defining the id field within a record inside the body, you can include custom information while still adhering to the structure expected by the HTTP module.