import ballerina/http;

type Student record {
    string Name;
    int Grade;
};

service /hello on new http:Listener(9090) {

    // The `Student` parameter in [Payload annotation](https://docs.central.ballerina.io/ballerina/http/latest/records/Payload)
    // represents the entity body of the inbound request.
    @http:ResourceConfig {
        consumes: ["application/json"]
    }
    resource function post bindStudent(@http:Payload Student student)
            returns json {
        string name = student.Name;
        return {Name: name};
    }

    //Binds the XML payload of the inbound request to the `store` variable.
    @http:ResourceConfig {
        consumes: ["application/xml"]
    }
    resource function post bindXML(@http:Payload xml store) returns xml {
        xml city = store.selectDescendants("{http://www.test.com}city");
        return city;
    }
}

Service Data Binding

HTTP service data binding helps to access the request payload through a resource signature parameter. The payload parameter should be declared with the @Payload annotation. string, json, xml, byte[], record, and record[] are supported as parameter types. Binding failures will be responded with 400[Bad Request] response

For more information on the underlying module, see the HTTP module.

import ballerina/http;
type Student record {
    string Name;
    int Grade;
};
service /hello on new http:Listener(9090) {
    @http:ResourceConfig {
        consumes: ["application/json"]
    }
    resource function post bindStudent(@http:Payload Student student)
            returns json {
        string name = student.Name;
        return {Name: name};
    }

The Student parameter in Payload annotation represents the entity body of the inbound request.

    @http:ResourceConfig {
        consumes: ["application/xml"]
    }
    resource function post bindXML(@http:Payload xml store) returns xml {
        xml city = store.selectDescendants("{http://www.test.com}city");
        return city;
    }
}

Binds the XML payload of the inbound request to the store variable.

bal run http_data_binding.bal
[ballerina/http] started HTTP/WS listener 0.0.0.0:9090
# To invoke the `bindStudent` resource, execute the below HTTP request.
curl http://localhost:9090/hello/bindStudent -d '{ "Name": "John", "Grade": 12, "Marks": {"English" : "85", "IT" : "100"}}' -H "Content-Type:application/json"
{"Name":"John"}%
# To invoke the `bindXML` resource, execute the below HTTP request.
curl http://localhost:9090/hello/bindXML -d "<h:Store id = \"AST\" xmlns:h=\"http://www.test.com\"><h:street>Main</h:street><h:city>94</h:city></h:Store>" -H "Content-Type:application/xml"
<h:city xmlns:h="http://www.test.com">94</h:city>%