DEV Community

Nethusha Ilukpitiya
Nethusha Ilukpitiya

Posted on

Building a Cloud-Native RESTful API with Ballerina and MySQL

As distributed architectures become standard, writing integration code in traditional general-purpose languages can be repetitive and heavy on boilerplate. Ballerina, an open-source programming language developed by WSO2, is engineered specifically for cloud-native integration and network-aware services.

In this project, I built a complete bookstore REST API that interfaces with a MySQL database using Ballerina.

Project Architecture

The application implements full CRUD operations for book inventory records (id, title, author, isbn, price, and stock):

service.bal: Exposes endpoints under /api/books using Ballerina's native HTTP listener.

db.bal: Handles MySQL database interactions using the ballerinax/mysql client.

types.bal: Defines structured data models for payload validation and schema safety.

Config.toml: Externalizes sensitive database credentials seamlessly.

Service Layer & Native Networking

Defining services and endpoints in Ballerina requires minimal boilerplate:

Code snippet
import ballerina/http;

service /api on new http:Listener(8080) {
resource function get books() returns Book[]|http:InternalServerError {
Book[]|sql:Error books = getAllBooks();
if books is error {
return http:InternalServerError{body: {message: "Internal server error"}};
}
return books;
}
}
Returning typed records like Book[] handles JSON serialization, HTTP headers, and status codes out of the box.

Database Persistence

Using ballerinax/mysql, queries leverage parameterized SQL statements to guard against SQL injection while mapping result sets into structured records.

Source Code

Full code and setup instructions are available on GitHub:

https://github.com/Nethusha2007/ballerina-bookstore-api

Top comments (0)