- Write a RESTful API with Ballerina
- Write a gRPC service with Ballerina
- Write a GraphQL API with Ballerina
- Work with data using queries in Ballerina
- Build a data service in Ballerina
- Build a Change Data Capture (CDC) service in Ballerina
- Work with Large Language Models (LLMs) using natural expressions
- Deploy Ballerina on Kubernetes
- Manage data persistence with bal persist
- Create your first connector with Ballerina
Configurability enables users to modify the system behavior through external user inputs. Ballerina Language provides an in-built functionality to configure values at runtime through configurable module-level variables.
Consider the following step-by-step guide to configuring a Ballerina package that contains an HTTP service.
-
Create a Ballerina package using the following command.
$ bal new greetings -
Replace the content of the file
main.balwith the following.
import ballerina/http; type Greeting record {| string to; string content; |}; configurable int port = 9090; configurable Greeting greeting = ?; service http:Service / on new http:Listener(port) { resource function post greeting() returns string { string message = string `Hello ${greeting.to}! ${greeting.content}`; return message; } }
Here, we created a Ballerina package named greetings that contains configurable variables port and greeting with
respective types int and Greeting. These variables are used in the HTTP service where the resource method
greeting() provides a configured message.
The variable port is initialized with a default value 9090, which indicates that the configuration is optional. This
value will be used for the variable initialization in case the configuration value will not be provided by the user at the runtime.
The variable greeting is initialized with the ? syntax, which indicates that providing a configuration value is mandatory. Therefore,
the program will finish the execution abruptly with a runtime exception, if the value is not provided at the runtime.
-
To provide the values for
portandgreetingthrough a configuration file, create a file namedConfig.tomlwith the following content in the current working directory.port = 8080 [greeting] to = "Tom" content = "Good Morning!" -
Execute the following command to build and execute the program.
$ bal runThe output will be as follows.
Compiling source sample/greetings:0.1.0 Running executableThis will start the HTTP service on the configured endpoint
8080. -
To verify the configuration, execute the following command.
$ curl http://localhost:8080/greeting -X POSTThe response will be similar to the following.
Hello Tom! Good Morning!