Skip to main content

Ballerina by Example

Ballerina by Example (BBE) is a collection of over 200 runnable code examples that demonstrate Ballerina language features and library capabilities. Each example includes source code, expected output, and can be executed directly. All examples are hosted on ballerina.io/learn/by-example.

Language concepts

Basics

ExampleDescription
Hello WorldMinimal Ballerina program
Programs and ModulesModule structure and imports
Variables and TypesVariable declarations and basic types
FunctionsFunction definitions and calls
StringsString operations and templates
If/ElseConditional statements
While LoopWhile loop iteration
ForeachForeach loop iteration
Match StatementPattern matching

Type system

ExampleDescription
IntegersInteger type and operations
Floating PointFloat and decimal types
Nil TypeWorking with nil values
Any TypeThe any and anydata types
Union TypesUnion type definitions
Type DefinitionsCustom type definitions
Type InferenceLet type inference
CovarianceType covariance

Records and maps

ExampleDescription
RecordsRecord type definitions
Open RecordsOpen vs closed records
Default ValuesRecord field defaults
Optional FieldsOptional record fields
MapsMap type and operations
Record to JSONConverting records to JSON

Arrays and tuples

ExampleDescription
ArraysArray type and operations
TuplesTuple types
List Sub TypingList type relationships
TableTable type and operations

Error handling

ExampleDescription
Error TypeError value creation
Check ExpressionError propagation with check
Error SubtypingCustom error types
Trap ExpressionCatching panics
On Fail ClauseHandling errors in blocks
Error DetailError detail records
RetryRetry operations

Concurrency

ExampleDescription
WorkersNamed workers
Worker Message PassingInter-worker communication
Wait ExpressionWaiting for workers
Alternate WaitWait for first result
Multiple WaitWait for all results
StrandStrand scheduling
LockMutual exclusion
Isolated FunctionsCompile-time concurrency safety

Transactions

ExampleDescription
TransactionsBasic transaction blocks
Check in TransactionsError handling in transactions
RollbackTransaction rollback
Retry TransactionsAutomatic retry
Transactional FunctionsParticipating functions

Query expressions

ExampleDescription
Query ExpressionsBasic query syntax
SortSort with order by
LimitLimit results
JoinTable joins
AggregationLet clause and aggregation

AI integrations

ExampleDescription
Direct LLM CallsSingle-shot calls to a large language model
Direct LLM Calls with HistoryConversational LLM calls with chat history
Direct LLM Calls with Multimodal InputPass images and other media to an LLM
RAG with In-Memory Vector StoreRetrieval-augmented generation using an in-memory store
RAG Ingestion (External Store)Index documents into an external vector store
RAG Query (External Store)Query an external vector store for grounded answers
MCP ServiceExpose tools through a Model Context Protocol server
MCP Advanced ServiceAdvanced MCP server features
AI Agent with Local ToolsAgent that calls local Ballerina functions as tools
AI Agent with MCP IntegrationAgent backed by tools served from an MCP server
AI Agent with External EndpointsAgent that calls external HTTP APIs as tools
Chat AgentsMulti-turn conversational AI agent
AI Agent with Tool KitsAgent organized around grouped tool kits
Natural ExpressionsUse the natural expression to call LLMs inline

Network libraries

HTTP

ExampleDescription
HTTP ServiceBasic HTTP service
HTTP ClientBasic HTTP client
Query ParametersService query parameters
Path ParametersService path parameters
Request/ResponseFull request/response handling
HeadersHTTP header handling
Data BindingPayload data binding
Error HandlingHTTP error handling
InterceptorsHTTP interceptors
CORSCross-origin resource sharing
Circuit BreakerCircuit breaker pattern
Load BalancerClient-side load balancing
RetryHTTP retry
CachingHTTP response caching
SSL/TLSHTTPS support
Mutual SSLMutual TLS authentication
Basic AuthBasic authentication
JWT AuthJWT authentication
OAuth2OAuth 2.0 authentication

gRPC

ExampleDescription
Unary RPCSimple unary gRPC
Server StreamingServer-side streaming
Client StreamingClient-side streaming
Bidirectional StreamingBidirectional streaming

GraphQL

ExampleDescription
GraphQL ServiceBasic GraphQL service
MutationsGraphQL mutations
Input TypesGraphQL input types
SubscriptionsGraphQL subscriptions
GraphQL Client QueryQuery a GraphQL endpoint from a client
Client Partial ResponseHandle partial responses on the client
Client Error HandlingHandle error responses on the client

WebSocket

ExampleDescription
WebSocket ServiceBasic WebSocket server
WebSocket ClientWebSocket client
Service Send/ReceiveSend and receive messages on a WebSocket service
Service Payload ValidationValidate incoming payloads with constraints
Service Error HandlingHandle errors on a WebSocket service
Client Payload ValidationValidate payloads from a WebSocket client

MQTT

ExampleDescription
MQTT ServiceSubscribe to messages from an MQTT broker
MQTT ClientPublish messages to an MQTT broker

TCP and UDP

ExampleDescription
TCP ServiceSend and receive bytes on a TCP listener
TCP ClientSend and receive bytes from a TCP client
UDP ServiceSend and receive datagrams on a UDP listener
UDP ClientSend and receive datagrams from a UDP client
UDP Connected ClientSend and receive datagrams over a connected UDP client

Messaging

ExampleDescription
Kafka ProducerKafka message producer
Kafka ConsumerKafka message consumer
Kafka Service: ConsumeConsume messages with a Kafka service
Kafka Service: ConstraintsValidate Kafka message payloads
Kafka Service: ErrorsHandle errors in a Kafka service
RabbitMQ ProducerRabbitMQ publisher
RabbitMQ ConsumerRabbitMQ consumer
RabbitMQ Acknowledged ConsumerConsumer with client acknowledgement
RabbitMQ Transactional ConsumerConsumer in a transactional context
RabbitMQ Queue DeclareDeclare a queue from a client
NATS SubscribeConsume messages from a NATS subject
NATS PublishPublish messages to a NATS subject
NATS Request/ReplySend a request and receive a reply
NATS Service ReplyReply from a NATS service
NATS JetStreamPublish through JetStream

Database

ExampleDescription
MySQL ClientMySQL database operations
SQL QueryQuery
Batch ExecuteBatch SQL operations
Call ProcedureCall stored procedures

Common libraries

File and I/O

ExampleDescription
Read/Write FilesFile I/O operations
Read/Write CSVCSV file processing
Read/Write JSONJSON file processing
Read/Write XMLXML file processing
FTP ClientFTP file operations
FTP ListenerFTP file event listener

Security

ExampleDescription
CryptoCryptographic operations
JWT Issue/ValidateJWT token operations
EncodingURL encoding/decoding

Testing

ExampleDescription
Test AssertionsTest assertion functions
Before/After FunctionsTest lifecycle hooks
Data-Driven TestsParameterized tests
MockingMock functions and clients

Observability

ExampleDescription
LoggingStructured logging
Counter MetricsPrometheus counters
Gauge MetricsPrometheus gauges
TracingDistributed tracing

Running examples locally

Each example can be run locally with:

# Clone the examples repository
git clone https://github.com/ballerina-platform/ballerina-distribution.git

# Navigate to an example
cd ballerina-distribution/examples/hello-world

# Run the example
bal run

Alternatively, use the "Run" button on each example page at ballerina.io/learn/by-example.

See also