Ballerina is an open-source programming language for the cloud that makes it easier to use, combine, and create network services.
import ballerina/http;
configurable int port = 8080;
type Album readonly & record {|
string id;
string title;
string artist;
decimal price;
|};
table<Album> key(id) albums = table [
{id: "1", title: "Blue Train", artist: "John Coltrane", price: 56.99},
{id: "2", title: "Jeru", artist: "Gerry Mulligan", price: 17.99},
{id: "3", title: "Sarah Vaughan and Clifford Brown", artist: "Sarah Vaughan", price: 39.99}
];
service / on new http:Listener(port) {
resource function get albums() returns Album[] {
return albums.toArray();
}
resource function get albums/[string id]() returns Album|http:NotFound {
Album? album = albums[id];
if album is () {
return <http:NotFound>{};
} else {
return album;
}
}
resource function post albums(@http:Payload Album album) returns Album {
albums.add(album);
return album;
}
}
import ballerina/http;
import ballerinax/googleapis.sheets;
configurable string githubPAT = ?;
configurable string repository = "ballerina-platform/ballerina-lang";
configurable string sheetsAccessToken = ?;
configurable string spreadSheetId = ?;
configurable string sheetName = "Sheet1";
type PR record {
string url;
string title;
string state;
string created_at;
string updated_at;
};
public function main() returns error? {
http:Client github = check new ("https://api.github.com/repos");
map<string> headers = {
"Accept": "application/vnd.github.v3+json",
"Authorization": "token " + githubPAT
};
PR[] prs = check github->get(string `/${repository}/pulls`, headers);
sheets:Client gsheets = check new ({auth: {token: sheetsAccessToken}});
check gsheets->appendRowToSheet(spreadSheetId, sheetName,
["Issue", "Title", "State", "Created At", "Updated At"]);
foreach var {url, title, state, created_at, updated_at} in prs {
check gsheets->appendRowToSheet(spreadSheetId, sheetName,
[url, title, state, created_at, updated_at]);
}
}
import ballerina/http;
import ballerina/io;
type Country record {
string country;
int population;
string continent;
int cases;
int deaths;
};
// Prints the top 10 countries having the highest case-fatality ratio.
public function main() returns error? {
http:Client diseaseEp = check new ("https://disease.sh/v3");
Country[] countries = check diseaseEp->get("/covid-19/countries");
json summary =
from var {country, continent, population, cases, deaths} in countries
where population >= 100000 && deaths >= 100
let decimal caseFatalityRatio = <decimal>deaths / <decimal>cases * 100
order by caseFatalityRatio descending
limit 10
select {country, continent, population, caseFatalityRatio};
io:println(summary);
}
import ballerina/grpc;
configurable int port = 9090;
Album[] albums = [
{id: "1", title: "Blue Train", artist: "John Coltrane", price: 56.99},
{id: "2", title: "Jeru", artist: "Gerry Mulligan", price: 17.99},
{id: "3", title: "Sarah Vaughan and Clifford Brown", artist: "Sarah Vaughan", price: 39.99}
];
@grpc:ServiceDescriptor {
descriptor: ROOT_DESCRIPTOR_RECORD_STORE,
descMap: getDescriptorMapRecordStore()
}
service "Albums" on new grpc:Listener(port) {
remote function getAlbum(string id) returns Album|error {
Album[] filteredAlbums = albums.filter(album => album.id == id);
if filteredAlbums.length() > 0 {
return filteredAlbums.pop();
}
return error grpc:NotFoundError(string `Cannot find the album for ID ${id}`);
}
remote function addAlbum(Album album) returns Album|error {
albums.push(album);
return album;
}
remote function listAlbums() returns stream<Album, error?>|error {
return albums.toStream();
}
}
syntax = "proto3";
import "google/protobuf/wrappers.proto";
import "google/protobuf/empty.proto";
service Albums {
rpc getAlbum(google.protobuf.StringValue)
returns (Album);
rpc addAlbum(Album) returns (Album);
rpc listAlbums(google.protobuf.Empty)
returns (stream Album);
}
message Album {
string id = 1;
string title = 2;
string artist = 3;
float price = 4;
};
import ballerina/graphql;
import ballerina/http;
import ballerinax/mysql;
import ballerinax/mysql.driver as _;
configurable string user = ?;
configurable string password = ?;
configurable string host = ?;
configurable int port = ?;
configurable string database = ?;
configurable string apiEndpoint = ?;
public type Album record {
string id;
string title;
string artist;
decimal price;
Currency currency = USD;
};
public enum Currency {
USD,
LKR,
EUR,
GBP
}
service / on new graphql:Listener(9000) {
private final mysql:Client db;
private final http:Client forex;
private final Currency baseCurrency = USD;
function init() returns error? {
self.db = check new (host, user, password, database, port);
self.forex = check new (apiEndpoint);
}
resource function get album(string id, Currency currency = USD) returns Album|error {
Album album = check self.db->queryRow(`SELECT * FROM Albums WHERE id=${id}`);
if currency != self.baseCurrency {
string query = string `from=${self.baseCurrency}&to;=${currency}`;
record {decimal rate;} exchange = check self.forex->get(string `/curerncyConversion?${query}`);
album.price = album.price * exchange.rate;
album.currency = currency;
}
return album;
}
}
import ballerina/http;
import ballerina/sql;
import ballerinax/mysql;
import ballerinax/mysql.driver as _;
configurable string host = ?;
configurable int port = ?;
configurable string user = ?;
configurable string password = ?;
configurable string database = ?;
type Album record {|
string id;
string title;
string artist;
decimal price;
|};
service / on new http:Listener(8080) {
private final mysql:Client db;
function init() returns error? {
self.db = check new (host, user, password, database, port);
}
resource function get albums() returns Album[]|error? {
stream<Album, sql:Error?> albumStream = self.db->query(`SELECT * FROM Albums`);
Album[]? albums = check from Album album in albumStream select album;
check albumStream.close();
return albums;
}
resource function get albums/[string id]() returns Album|http:NotFound|error {
Album|sql:Error result = self.db->queryRow(`SELECT * FROM Albums WHERE id = ${id}`);
if result is sql:NoRowsError {
return <http:NotFound>{};
} else {
return result;
}
}
resource function post album(@http:Payload Album album) returns Album|error {
_ = check self.db->execute(`
INSERT INTO Albums (id, title, artist, price)
VALUES (${album.id}, ${album.title}, ${album.artist}, ${album.price});`);
return album;
}
}
import ballerina/lang.value;
import ballerinax/kafka;
configurable string groupId = "order-consumers";
configurable string orders = "orders";
configurable string paymentSuccessOrders = "payment-success-orders";
configurable decimal pollingInterval = 1;
configurable string kafkaEndpoint = kafka:DEFAULT_URL;
type Order readonly & record {|
int id;
string desc;
PaymentStatus paymentStatus;
|};
enum PaymentStatus {
SUCCESS,
FAIL
}
final kafka:ConsumerConfiguration consumerConfigs = {
groupId: groupId,
topics: [orders],
offsetReset: kafka:OFFSET_RESET_EARLIEST,
pollingInterval: pollingInterval
};
service on new kafka:Listener(kafkaEndpoint, consumerConfigs) {
private final kafka:Producer orderProducer;
function init() returns error? {
self.orderProducer = check new (kafkaEndpoint);
}
remote function onConsumerRecord(kafka:ConsumerRecord[] records) returns error? {
check from kafka:ConsumerRecord {value} in records
let string orderString = check string:fromBytes(value)
let Order 'order = check value:fromJsonStringWithType(orderString)
where 'order.paymentStatus == SUCCESS
do {
check self.orderProducer->send({
topic: paymentSuccessOrders,
value: 'order.toString().toBytes()
});
};
}
}
Network primitives in the language make it simpler to write services and run them in the cloud.
Structural types with support for openness are used both for static typing within a program and for describing service interfaces.
Type-safe, declarative processing of JSON, XML, and tabular data with language-integrated queries.
Programs have both a textual syntax and an equivalent graphical form based on sequence diagrams.
Easy and efficient concurrency with sequence diagrams and language-managed threads without the complexity of asynchronous functions.
Explicit error handling, static types, and concurrency safety, combined with a familiar, readable syntax make programs reliable and maintainable.
May 25, 2022 Wed., 6.30 p.m. PDT Online |
Meetup Ballerina: A Language to Develop, Consume and Combine Network ServicesSameera Jayasoma, Senior Director, WSO2 |
More info |
June 8, 2022 Wed., 6.10 a.m. EDT Online |
Women in Tech Global Conference Ballerina: Cloud-Native Middleware as a Programming LanguageAnupama Pathirage, Director of Engineering, WSO2 |
More info |
This website uses cookies so that we can provide you with the best user experience. Read our Cookie policy to find out more.
If you wish to disable cookies you can do so from your browser.