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
| Example | Description |
|---|---|
| Hello World | Minimal Ballerina program |
| Programs and Modules | Module structure and imports |
| Variables and Types | Variable declarations and basic types |
| Functions | Function definitions and calls |
| Strings | String operations and templates |
| If/Else | Conditional statements |
| While Loop | While loop iteration |
| Foreach | Foreach loop iteration |
| Match Statement | Pattern matching |
Type system
| Example | Description |
|---|---|
| Integers | Integer type and operations |
| Floating Point | Float and decimal types |
| Nil Type | Working with nil values |
| Any Type | The any and anydata types |
| Union Types | Union type definitions |
| Type Definitions | Custom type definitions |
| Type Inference | Let type inference |
| Covariance | Type covariance |
Records and maps
| Example | Description |
|---|---|
| Records | Record type definitions |
| Open Records | Open vs closed records |
| Default Values | Record field defaults |
| Optional Fields | Optional record fields |
| Maps | Map type and operations |
| Record to JSON | Converting records to JSON |
Arrays and tuples
| Example | Description |
|---|---|
| Arrays | Array type and operations |
| Tuples | Tuple types |
| List Sub Typing | List type relationships |
| Table | Table type and operations |
Error handling
| Example | Description |
|---|---|
| Error Type | Error value creation |
| Check Expression | Error propagation with check |
| Error Subtyping | Custom error types |
| Trap Expression | Catching panics |
| On Fail Clause | Handling errors in blocks |
| Error Detail | Error detail records |
| Retry | Retry operations |
Concurrency
| Example | Description |
|---|---|
| Workers | Named workers |
| Worker Message Passing | Inter-worker communication |
| Wait Expression | Waiting for workers |
| Alternate Wait | Wait for first result |
| Multiple Wait | Wait for all results |
| Strand | Strand scheduling |
| Lock | Mutual exclusion |
| Isolated Functions | Compile-time concurrency safety |
Transactions
| Example | Description |
|---|---|
| Transactions | Basic transaction blocks |
| Check in Transactions | Error handling in transactions |
| Rollback | Transaction rollback |
| Retry Transactions | Automatic retry |
| Transactional Functions | Participating functions |
Query expressions
| Example | Description |
|---|---|
| Query Expressions | Basic query syntax |
| Sort | Sort with order by |
| Limit | Limit results |
| Join | Table joins |
| Aggregation | Let clause and aggregation |
AI integrations
| Example | Description |
|---|---|
| Direct LLM Calls | Single-shot calls to a large language model |
| Direct LLM Calls with History | Conversational LLM calls with chat history |
| Direct LLM Calls with Multimodal Input | Pass images and other media to an LLM |
| RAG with In-Memory Vector Store | Retrieval-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 Service | Expose tools through a Model Context Protocol server |
| MCP Advanced Service | Advanced MCP server features |
| AI Agent with Local Tools | Agent that calls local Ballerina functions as tools |
| AI Agent with MCP Integration | Agent backed by tools served from an MCP server |
| AI Agent with External Endpoints | Agent that calls external HTTP APIs as tools |
| Chat Agents | Multi-turn conversational AI agent |
| AI Agent with Tool Kits | Agent organized around grouped tool kits |
| Natural Expressions | Use the natural expression to call LLMs inline |
Network libraries
HTTP
| Example | Description |
|---|---|
| HTTP Service | Basic HTTP service |
| HTTP Client | Basic HTTP client |
| Query Parameters | Service query parameters |
| Path Parameters | Service path parameters |
| Request/Response | Full request/response handling |
| Headers | HTTP header handling |
| Data Binding | Payload data binding |
| Error Handling | HTTP error handling |
| Interceptors | HTTP interceptors |
| CORS | Cross-origin resource sharing |
| Circuit Breaker | Circuit breaker pattern |
| Load Balancer | Client-side load balancing |
| Retry | HTTP retry |
| Caching | HTTP response caching |
| SSL/TLS | HTTPS support |
| Mutual SSL | Mutual TLS authentication |
| Basic Auth | Basic authentication |
| JWT Auth | JWT authentication |
| OAuth2 | OAuth 2.0 authentication |
gRPC
| Example | Description |
|---|---|
| Unary RPC | Simple unary gRPC |
| Server Streaming | Server-side streaming |
| Client Streaming | Client-side streaming |
| Bidirectional Streaming | Bidirectional streaming |
GraphQL
| Example | Description |
|---|---|
| GraphQL Service | Basic GraphQL service |
| Mutations | GraphQL mutations |
| Input Types | GraphQL input types |
| Subscriptions | GraphQL subscriptions |
| GraphQL Client Query | Query a GraphQL endpoint from a client |
| Client Partial Response | Handle partial responses on the client |
| Client Error Handling | Handle error responses on the client |
WebSocket
| Example | Description |
|---|---|
| WebSocket Service | Basic WebSocket server |
| WebSocket Client | WebSocket client |
| Service Send/Receive | Send and receive messages on a WebSocket service |
| Service Payload Validation | Validate incoming payloads with constraints |
| Service Error Handling | Handle errors on a WebSocket service |
| Client Payload Validation | Validate payloads from a WebSocket client |
MQTT
| Example | Description |
|---|---|
| MQTT Service | Subscribe to messages from an MQTT broker |
| MQTT Client | Publish messages to an MQTT broker |
TCP and UDP
| Example | Description |
|---|---|
| TCP Service | Send and receive bytes on a TCP listener |
| TCP Client | Send and receive bytes from a TCP client |
| UDP Service | Send and receive datagrams on a UDP listener |
| UDP Client | Send and receive datagrams from a UDP client |
| UDP Connected Client | Send and receive datagrams over a connected UDP client |
Messaging
| Example | Description |
|---|---|
| Kafka Producer | Kafka message producer |
| Kafka Consumer | Kafka message consumer |
| Kafka Service: Consume | Consume messages with a Kafka service |
| Kafka Service: Constraints | Validate Kafka message payloads |
| Kafka Service: Errors | Handle errors in a Kafka service |
| RabbitMQ Producer | RabbitMQ publisher |
| RabbitMQ Consumer | RabbitMQ consumer |
| RabbitMQ Acknowledged Consumer | Consumer with client acknowledgement |
| RabbitMQ Transactional Consumer | Consumer in a transactional context |
| RabbitMQ Queue Declare | Declare a queue from a client |
| NATS Subscribe | Consume messages from a NATS subject |
| NATS Publish | Publish messages to a NATS subject |
| NATS Request/Reply | Send a request and receive a reply |
| NATS Service Reply | Reply from a NATS service |
| NATS JetStream | Publish through JetStream |
Database
| Example | Description |
|---|---|
| MySQL Client | MySQL database operations |
| SQL Query | Query |
| Batch Execute | Batch SQL operations |
| Call Procedure | Call stored procedures |
Common libraries
File and I/O
| Example | Description |
|---|---|
| Read/Write Files | File I/O operations |
| Read/Write CSV | CSV file processing |
| Read/Write JSON | JSON file processing |
| Read/Write XML | XML file processing |
| FTP Client | FTP file operations |
| FTP Listener | FTP file event listener |
Security
| Example | Description |
|---|---|
| Crypto | Cryptographic operations |
| JWT Issue/Validate | JWT token operations |
| Encoding | URL encoding/decoding |
Testing
| Example | Description |
|---|---|
| Test Assertions | Test assertion functions |
| Before/After Functions | Test lifecycle hooks |
| Data-Driven Tests | Parameterized tests |
| Mocking | Mock functions and clients |
Observability
| Example | Description |
|---|---|
| Logging | Structured logging |
| Counter Metrics | Prometheus counters |
| Gauge Metrics | Prometheus gauges |
| Tracing | Distributed 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
- Ballerina API Documentation — Full API docs
- Ballerina Specifications — Language and platform specifications