DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. Getting Started With Ballerina in 10 Minutes

Getting Started With Ballerina in 10 Minutes

Ballerina is a new programming langauge built with the mind of writing network services and functions. Writing network services and functions within it is quick and easy!

Chanaka Fernando user avatar by
Chanaka Fernando
CORE ·
Mar. 08, 17 · Tutorial
Like (4)
Save
Tweet
Share
7.57K Views

Join the DZone community and get the full member experience.

Join For Free

Ballerina is the latest revelation in programming languages. It has been built with the mind of writing network services and functions. With this post, I’m going to describe how to write network services and functions within a 10-minute tutorial.

First, go to the ballerinalang website and download the latest Ballerina tools distribution, which has the runtime and all the tools required for writing Ballerina programs. After downloading, you can extract the archive into a directory (let’s say BALLERINA_HOME) and set the PATH environment variable to the bin directory of BALLERINA_HOME, in which you have extracted the downloaded tools distribution. In linux, you can achieve this as mentioned below:

export PATH = $PATH:/BALLERINA_HOME/bin

Or, for example, export PATH = $PATH:/Users/chanaka-mac/ballerinalang/Testing/ballerina-tools-0.8.3/bin.

Now, you have set up Ballerina in your system. Now, it is time to run the first example of all: the Hello World example. Ballerina can be used to write two types of programs.

  1. Network services.
  2. Main functions.

Here, network services are long running services which keeps on running after it is started until the process is killed or stopped by external party. Main functions are programs which executes a given task and exit by itself.

Let’s run the more familiar main program style Hello World example. The only thing you have to do is run the Ballerina command pointing to the Hello World sample. Change your directory to the samples directory within Ballerina tools distribution ($BALLERINA_HOME/samples). Now, run the following command from your terminal:

$ ballerina run main helloWorld/helloWorld.bal

Once you run the above command, you will see the output “Hello, World!” and you are all set (voila!).

Let’s go to the file and see how a Ballerina Hello World program looks.

import ballerina.lang.system;
function main(string[] args) {    
  system:println("Hello, World!");
}
  • Signature of the main function is similar to other programming languages like C and Java.
  • You need to import native utilities before using them (no auto-import).
  • How to run the program using the Ballerina run command.

Now, the basics are covered. Let’s move on to the next step. Which is running a service that says “Hello, World!” and keeps on running.

All you have to do is execute the below command in your terminal:

$ ballerina run service helloWorldService/helloWorldService.bal
ballerina: deploying service(s) in 'helloWorldService/helloWorldService.bal'
ballerina: started server connector http-9090

Now, things are getting little bit interesting. You can see two lines that describe what has happened with the above command. It has deployed a service that was described the the mentioned file and there is a port (9090) opened for HTTP communication.

Now, this service is started and listening on port 9090. We need to send a request to get the response out of this service. If you browse to the README.txt within the helloWorldService sample directory, you can find the below curl command which can be used to invoke this service. Let’s run this command from another command window.

$ curl -v http://localhost:9090/hello
> GET /hello HTTP/1.1
> Host: localhost:9090
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/plain
< Content-Length: 13
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
Hello, World!

You can see that we got a response message from the service saying “Hello, World!” Let’s crack into the program which does this. Go the Ballerina file within helloWorldService/helloWorldService.bal.

import ballerina.lang.messages;
@http:BasePath ("/hello")
service helloWorld {

    @http:GET
    resource sayHello (message m) {
        message response = {};
        messages:setStringPayload(response, "Hello, World!");
        reply response;

    }

}

This program covers several important aspects of a Ballerina program:

  • Annotations are used to define the service related entities. In this sample, “/hello” is the context of the service and “GET” is the HTTP method accepted by this service.
  • Message is the data carrier coming from the client. Users can do what ever they want with message and they can create new messages and many other things.
  • The “reply” statement is used to send a reply back to the service client.

In the above example, we have created a new message called “response” and set the payload as “Hello, World!” and then replied back to the client. The way you executed this service was curl -v http://localhost:9090/hello.

In the above command, we specified the port (9090) which the service was started and the context (/hello) we defined in the code.

We have few mins left, let’s go for another sample which is bit more advanced and completes the set.

Execute the following command in your terminal.

$ballerina run service passthroughService/passthroughService.bsz
ballerina: deploying service(s) in 'passthroughService/passthroughService.bsz'
ballerina: started server connector http-9090

Here, we have run a file with a different extension (BSZ) but the result was similar to the previous section. File has been deployed and the port is opened. Let’s quickly invoke this service with the following command as mentioned in the README.txt file.

$ curl -v http://localhost:9090/passthrough
> GET /passthrough HTTP/1.1
> Host: localhost:9090
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 49
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
{"exchange":"nyse","name":"IBM","value":"127.50"}

Now, we get an interesting response. Let’s go inside the source and see what we have just executed. This sample is bit advanced and hence it covers several other important features we have not mentioned in previous sections.

  • Ballerina programs can be run as a self-contatining archive. In this sample, we have run service archive file (.bsz) which contains all the artifacts required to run this service.
  • Ballerina programs can have packages and the package structure follows the directory structure. In this sample, we have a package called “passthroughservice.samples” and the directory structure is similar passthroughservice/samples.

Here are the contents of this sample.

passthroughService.bal:

package passthroughservice.samples;
import ballerina.net.http;
@http:BasePath ("/passthrough")
service passthrough {
@http:GET
    resource passthrough (message m) {
        http:ClientConnector nyseEP = create http:ClientConnector("http://localhost:9090");
        message response = http:ClientConnector.get(nyseEP, "/nyseStock", m);
        reply response;
}
}

nyseStockService.bal:

package passthroughservice.samples;
import ballerina.lang.messages;
@http:BasePath ("/nyseStock")
service nyseStockQuote {
@http:GET
    resource stocks (message m) {
        json payload = `{"exchange":"nyse", "name":"IBM", "value":"127.50"}`;
        message response = {};
        messages:setJsonPayload(response, payload);
        reply response;
}
}

In this sample, we have written a simple integration by conncting to another service which is also written in Ballerina and running on the same runtime. “passthroughService.bal” contains the main Ballerina service logic in which:

  • Create a client connector to the backend service,
  • Send a GET request to a given path with the incoming message,
  • Reply back the response from the backend service,

In this sample, we have written the back end service also from ballerina. In that service “nyseStockService.bal” —

  • Create a JSON message with the content.
  • Set that message as the payload of a new message.
  • Reply back to the client (which is the passthroughService).

It’s done! Now, you can run the remainder of the sample or write your own programs using Ballerina. Happy dancing!

Ballerina (programming language) Command (computing) Archive file

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Microservices 101: Transactional Outbox and Inbox
  • Building a Real-Time App With Spring Boot, Cassandra, Pulsar, React, and Hilla
  • Journey to Event Driven, Part 1: Why Event-First Programming Changes Everything
  • Important Takeaways for PostgreSQL Indexes

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: