Ballerina (programming language): Difference between revisions

Content deleted Content added
PubuduF (talk | contribs)
Update hello world example to Ballerina 2201.0.0 version
PubuduF (talk | contribs)
Add REST API example
Line 44:
=== Hello World ===
The regular Hello World program:
<syntaxhighlight>
{{pre|
import ballerina/io;
 
Line 50:
io:println("Hello World!");
}
</syntaxhighlight>
}}
 
To execute the above program, place the source code in a <code>.bal</code> file and provide the path of the file to the <code>bal run</code> command.
Line 60:
 
The service version of the Hello World program:
<syntaxhighlight>
{{pre|
import ballerina/http;
 
Line 68:
}
}
</syntaxhighlight>
}}
 
Services are executed in the same manner, except they don't terminate like regular programs do. Once the service is up and running, one can use an HTTP client to invoke the service. For example, the above service can be invoked using the following cURL command:
Line 78:
 
<ref name="example1">{{cite web |url=https://ballerina.io/learn/by-example/hello-world-service.html |title= Hello world service |author=Ballerina Team|date=16 September 2020 |publisher=ballerina.io}}</ref>
 
=== REST API ===
<syntaxhighlight>
import ballerina/http;
 
service on new http:Listener(9090) {
resource function post factorial(@http:Payload string payload) returns http:Ok|http:BadRequest {
int|error num = int:fromString(payload);
 
if num is error {
return <http:BadRequest>{body: "Invalid integer: " + payload};
}
 
if num < 0 {
return <http:BadRequest>{body: "Integer should be >= 0"};
}
 
int result = 1;
 
foreach int i in 2 ... num {
result *= i;
}
 
return <http:Ok>{body: result};
}
}}
</syntaxhighlight>
 
<syntaxhighlight lang="console">
$ curl http://localhost:9090/factorial -d 5
120
</syntaxhighlight>
 
=== Workers ===