import ballerina/http;
import ballerina/mime;
endpoint http:Listener echoEP {
port:9090
};
@http:ServiceConfig { basePath:"/foo" }
service<http:Service> echo bind echoEP {
@http:ResourceConfig {
methods:["POST"],
path:"/bar"
}
echo (endpoint conn, http:Request req) {
var result = req.getJsonPayload();
http:Response res = new;
match result {
http:PayloadError err => {
res.statusCode = 500;
res.setStringPayload(err.message);
}
json value =>{
res.setJsonPayload(value);
}
}
_ = conn -> respond(res);
}
}
Base Path and PathBallerina supports writing RESTful services according to the JAX-RS specification. You can use BasePath, Path, and HTTP verb annotations such as POST and GET to constrain your service in a RESTful manner. |
|
import ballerina/http;
import ballerina/mime;
|
|
endpoint http:Listener echoEP {
port:9090
};
|
Attributes associated with the service endpoint is defined here. |
@http:ServiceConfig { basePath:"/foo" }
service<http:Service> echo bind echoEP {
|
The BasePath attribute associates a path to the service. It binds the service endpoint to the service. |
@http:ResourceConfig {
methods:["POST"],
path:"/bar"
}
echo (endpoint conn, http:Request req) {
|
The POST annotation restricts the resource to accept POST requests only. Similarly, there are different annotations for each HTTP verb. The Path attribute associates a subpath to the resource. |
var result = req.getJsonPayload();
http:Response res = new;
match result {
http:PayloadError err => {
res.statusCode = 500;
res.setStringPayload(err.message);
}
json value =>{
res.setJsonPayload(value);
}
}
|
This method gets the request payload. |
_ = conn -> respond(res);
}
}
|
Reply to the client with the response. |
$ ballerina run base-path-and-path.bal
ballerina: initiating service(s) in '.../base-path-and-path.bal'
ballerina: started HTTP/WS server connector 0.0.0.0:9090
|
|
$ curl http://localhost:9090/foo/bar -d "{\"hello\": \"world\"}" -H "Content-Type: application/json"
{"hello": "world"}
|
|