<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lasith Jayalath on Medium]]></title>
        <description><![CDATA[Stories by Lasith Jayalath on Medium]]></description>
        <link>https://medium.com/@lasithmanaram?source=rss-be94a785d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iatYeVZjlBf8Hhv661B_7A@2x.jpeg</url>
            <title>Stories by Lasith Jayalath on Medium</title>
            <link>https://medium.com/@lasithmanaram?source=rss-be94a785d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 13:12:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lasithmanaram/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Rewriting Software with AI Agents: The Future of Code Modernization]]></title>
            <link>https://lasithmanaram.medium.com/rewriting-software-with-ai-agents-the-future-of-code-modernization-bab9e661c448?source=rss-be94a785d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bab9e661c448</guid>
            <category><![CDATA[rewrite-software]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Lasith Jayalath]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 14:48:23 GMT</pubDate>
            <atom:updated>2025-11-09T14:48:23.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EwMd4Wgh9HqJHUxhOy3vtg.png" /></figure><p>In today’s rapidly evolving software landscape, rewriting or modernizing legacy systems is no longer just a maintenance task — it’s a survival necessity. But what if the next generation of software rewrites wasn’t driven solely by humans? What if autonomous <strong>AI agents</strong> could analyze, plan, and rewrite entire codebases for us?</p><p>Welcome to the emerging world of <strong>AI-driven software rewriting</strong> — where intelligent systems collaborate with developers to transform old code into modern, high-performance architectures.</p><h4>Why Software Rewrites Are So Hard</h4><p>Rewriting software is traditionally a daunting task.<br> Legacy systems often come with:</p><ul><li>Outdated frameworks and dependencies</li><li>Poor documentation</li><li>Tight coupling between components</li><li>Risk of breaking critical business logic</li></ul><p>Developers spend months (or even years) unraveling old logic before introducing improvements. The result? Costly rewrites and delayed innovation.</p><p>That’s where <strong>AI agents</strong> come in.</p><h4>What It Means to “Rewrite Software Using AI Agents”</h4><p>When we talk about <em>rewriting software with AI agents</em>, we’re referring to using <strong>autonomous or semi-autonomous systems</strong> powered by large language models (LLMs) and reasoning frameworks to:</p><ul><li>Understand existing codebases and their architecture</li><li>Identify performance bottlenecks, design flaws, or obsolete code</li><li>Automatically refactor or rewrite modules into a new language, framework, or structure</li><li>Validate the rewritten code with AI-generated tests and human-in-the-loop verification</li></ul><p>In essence, AI agents act like <em>virtual developers</em> capable of reading, planning, writing, and testing code — all while learning from your feedback.</p><h4>How It Works: The AI-Driven Rewrite Workflow</h4><p>Let’s break down the typical lifecycle of rewriting software with AI agents.</p><h4>1. Code Ingestion and Understanding</h4><p>The AI agent begins by scanning your source repository to build a <strong>semantic map</strong> of the code.<br> It identifies:</p><ul><li>Classes, functions, and variables</li><li>Inter-module dependencies</li><li>Data models, API endpoints, and external libraries</li></ul><p>This helps the agent “understand” the overall system structure.</p><p><strong>Tools used:</strong></p><ul><li>Sourcegraph Cody</li><li>OpenDevin</li><li>LLMs like GPT-5, Code Llama, or StarCoder</li><li>LangChain or LlamaIndex for knowledge indexing</li></ul><h4>2. Goal Definition</h4><p>You define <em>what kind of rewrite</em> you need:</p><ul><li><strong>Language migration:</strong> Python → Go</li><li><strong>Framework upgrade:</strong> AngularJS → React</li><li><strong>Performance refactor:</strong> optimize algorithms, remove redundancy</li><li><strong>Architecture shift:</strong> monolith → microservices</li></ul><p>The clearer your goal, the more accurate and useful the AI output will be.</p><h4>3. Analysis &amp; Planning</h4><p>The AI creates a <strong>migration plan</strong>, detailing:</p><ul><li>Which modules can be automatically converted</li><li>Which areas need human review</li><li>Dependency graphs showing rewrite order</li><li>Estimated effort and risk levels</li></ul><p>Some advanced agents even simulate potential runtime issues or suggest parallel execution strategies.</p><h4>4. Code Transformation</h4><p>Now the real work begins.<br> The AI agent rewrites the code using generative models — adhering to modern best practices such as:</p><ul><li>SOLID principles</li><li>Async I/O or reactive programming</li><li>Efficient data access patterns</li><li>Updated API contracts and error handling</li></ul><p>It can also recreate build scripts, configuration files, and CI/CD workflows.</p><h4>5. Automated Testing &amp; Validation</h4><p>Once rewritten, the AI system generates and runs tests to verify behavioral parity with the old code.<br> This includes:</p><ul><li>Unit and integration tests</li><li>Linting and static analysis</li><li>Test coverage reports</li></ul><p>If discrepancies are found, the agent flags them for human review or self-correction.</p><h4>6. Human-in-the-Loop Review</h4><p>AI doesn’t replace developers — it <em>augments</em> them.<br> You still review logic, fine-tune performance, and ensure business rules remain intact.<br> The agent learns from your feedback to improve subsequent rewrites.</p><h4>Common AI Tools &amp; Frameworks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*RovhsP6kp3TP5gvbhEjB_A.png" /></figure><h4>Real-World Scenarios</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*gtHZS4fcXoN0hKiDVf3cBA.png" /></figure><h4>Getting Started as a Beginner</h4><p>Here’s a simple roadmap to begin experimenting with AI-driven rewrites.</p><h4>Step 1: Learn the Basics of AI Agents</h4><p>Understand how multi-agent systems like <strong>LangChain</strong>, <strong>AutoGPT</strong>, or <strong>OpenDevin</strong> operate and coordinate tasks.</p><h4>Step 2: Start Small</h4><p>Pick a small open-source or personal project — for example, a Flask app — and use an AI tool (like ChatGPT or Copilot) to refactor a few modules.</p><h4>Step 3: Use AI-Assisted IDEs</h4><p>Integrate tools like <strong>Copilot</strong>, <strong>Codeium</strong>, or <strong>Cody</strong> to get intelligent code completion, rewrite suggestions, and test generation.</p><h4>Step 4: Automate Refactoring Tasks</h4><p>Ask your AI assistant to “convert this class to use async/await” or “rewrite this module for Python 3.12 compatibility.”</p><h4>Step 5: Scale Up</h4><p>Once you’re comfortable, use <strong>LangChain agents</strong> or <strong>OpenDevin</strong> to analyze and refactor entire repositories.</p><h3>Learning Path for Mastery</h3><ol><li><strong>AI + Software Engineering Fundamentals</strong></li></ol><ul><li>Understand LLMs, embeddings, and prompt engineering</li><li>Learn how AI models interpret and represent code</li></ul><p><strong>2. Hands-On Practice</strong></p><ul><li>Experiment with LangChain Agents and GitHub Copilot</li><li>Use repository-wide tools like Cody or OpenDevin</li></ul><p><strong>3. Advanced Projects</strong></p><ul><li>Automate testing pipelines with AI</li><li>Build a custom code-rewriting agent tailored to your tech stack</li></ul><h4>The Bigger Picture</h4><p>AI-assisted software rewriting isn’t just about convenience.<br> It’s about <strong>bridging decades of technical debt</strong>, <strong>accelerating modernization</strong>, and <strong>democratizing access to clean, maintainable code</strong>.</p><p>Instead of spending months unraveling legacy code, developers can focus on creativity, architecture, and innovation — while AI handles the heavy lifting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bab9e661c448" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Microservices with Ballerina and Kubernetes]]></title>
            <link>https://lasithmanaram.medium.com/scaling-microservices-with-ballerina-and-kubernetes-69158bc5d937?source=rss-be94a785d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/69158bc5d937</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[scaling-microservices]]></category>
            <dc:creator><![CDATA[Lasith Jayalath]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 03:45:01 GMT</pubDate>
            <atom:updated>2025-10-31T03:45:01.475Z</atom:updated>
            <content:encoded><![CDATA[<h4>Effortless Cloud-Native Deployment Without the YAML Headaches</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFC0YjmloB0qiYsCagmKbg.png" /></figure><p>Modern software systems increasingly rely on <strong>microservice architectures</strong> to achieve scalability, flexibility, and independent deployability. While microservices unlock these advantages, managing their deployment and scaling in <strong>Kubernetes (K8s)</strong> often brings operational complexity — especially when drowning in YAML configuration files.</p><p>This is where <strong>Ballerina</strong>, a cloud-native programming language by WSO2, changes the game. It simplifies the entire microservice lifecycle — from coding to containerization and orchestration — with <strong>built-in Kubernetes support</strong>.</p><p>In this article, we’ll explore how <strong>Ballerina’s Kubernetes annotations</strong> make scaling and deploying microservices <strong>seamless and developer-centric</strong>, without having to manually write a single line of YAML.</p><h4>The Challenge: Kubernetes Complexity</h4><p>Let’s be honest — Kubernetes is powerful, but writing and maintaining YAML manifests for <strong>Deployments</strong>, <strong>Services</strong>, <strong>Ingresses</strong>, and <strong>ConfigMaps</strong> can be painful.</p><p>Even for a simple microservice, you may need:</p><ul><li>A Deployment.yaml for pods and replicas</li><li>A Service.yaml for networking</li><li>An Ingress.yaml for external access</li><li>ConfigMap or Secret files for configurations</li></ul><p>As the number of microservices grows, so does the complexity of managing these manifests. Developers often spend more time configuring deployments than writing business logic.</p><h4>Enter Ballerina: Cloud-Native by Design</h4><p>Ballerina is not just another programming language — it’s built <strong>from the ground up for the cloud</strong>. Its syntax and semantics are designed around <strong>network interaction, concurrency, and distributed systems</strong>.</p><p>What makes it particularly powerful for microservices is that it comes with <strong>native support for Docker and Kubernetes</strong> — through <strong>annotations</strong> that automatically generate the required container and K8s artifacts during compilation.</p><p>You write your service logic in Ballerina, add a few simple annotations, and the compiler does the rest.</p><h4>Writing a Microservice in Ballerina</h4><p>Let’s start with a simple microservice written in Ballerina:</p><pre>import ballerina/http;<br><br>service /hello on new http:Listener(8080) {<br>    resource get say() returns string {<br>        return &quot;Hello from Ballerina!&quot;;<br>    }<br>}</pre><p>This defines a RESTful service at GET /hello/say running on port 8080.</p><p>Pretty straightforward — but now let’s see how we can <strong>deploy this to Kubernetes effortlessly</strong>.</p><h4>Adding Kubernetes Annotations</h4><p>Ballerina provides a set of annotations from the ballerinax/kubernetes module that can be attached to your services, listeners, and main functions.</p><p>Here’s how you can enable automatic container and Kubernetes deployment:</p><pre>import ballerina/http;<br>import ballerinax/kubernetes;<br><br>@kubernetes:Service {<br>    name: &quot;hello-service&quot;,<br>    port: 8080<br>}<br>@kubernetes:Deployment {<br>    imagePullPolicy: &quot;IfNotPresent&quot;,<br>    replicas: 3<br>}<br>@kubernetes:Ingress {<br>    hostname: &quot;ballerina-demo.com&quot;,<br>    path: &quot;/&quot;<br>}<br>service /hello on new http:Listener(8080) {<br>    resource get say() returns string {<br>        return &quot;Hello, Kubernetes from Ballerina!&quot;;<br>    }<br>}</pre><h4>What’s Happening Here?</h4><ul><li><strong>@kubernetes:Service</strong> — Defines a Kubernetes Service to expose the microservice.</li><li><strong>@kubernetes:Deployment</strong> — Generates a Deployment manifest, automatically containerizing the service with three replicas.</li><li><strong>@kubernetes:Ingress</strong> — Creates an Ingress resource for external access.</li><li>During compilation, Ballerina automatically:</li><li>Builds a Docker image</li><li>Generates Kubernetes YAML files</li><li>Packages everything ready for deployment</li></ul><p>You can find all generated artifacts under target/kubernetes/.</p><h4>Building and Deploying</h4><p>To build and deploy the service:</p><pre>bal build</pre><p>This command:</p><ul><li>Compiles your .bal source</li><li>Builds the Docker image</li><li>Generates Kubernetes YAML manifests</li><li>Creates a .jar for execution</li></ul><p>You can then deploy to Kubernetes easily:</p><pre>kubectl apply -f target/kubernetes/hello_service</pre><p>Boom! Your Ballerina microservice is now running on Kubernetes — without writing any YAML manually.</p><h4>Scaling with Ease</h4><p>Scaling in Kubernetes is as simple as updating the <strong>replica count</strong> in your annotation:</p><pre>@kubernetes:Deployment {<br>    replicas: 5<br>}</pre><p>Rebuild with bal build, apply the new manifest, and Kubernetes will scale your pods automatically.</p><p>You can also scale on the fly using:</p><pre>kubectl scale deployment hello-service-deployment --replicas=10</pre><p>Since the underlying architecture is pure Kubernetes, Ballerina works perfectly with <strong>Horizontal Pod Autoscalers (HPA)</strong>, <strong>Prometheus metrics</strong>, and <strong>service mesh</strong> tools like Istio.</p><h3>Observability Out of the Box</h3><p>Ballerina microservices integrate natively with <strong>OpenTelemetry</strong> for:</p><ul><li><strong>Distributed tracing</strong></li><li><strong>Metrics collection</strong></li><li><strong>Centralized logging</strong></li></ul><p>This makes it straightforward to monitor, debug, and optimize scaling behavior without needing extra libraries.</p><p>Example configuration:</p><pre>import ballerina/observe;<br><br>configurable boolean enableObservability = true;<br><br>service /hello on new http:Listener(8080) {<br>    resource get say() returns string {<br>        return &quot;Observability enabled!&quot;;<br>    }<br>}</pre><p>When enabled, metrics like request count, latency, and error rates are automatically exported to monitoring tools such as Prometheus or Grafana.</p><h4>Why Ballerina + Kubernetes = A Perfect Match</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*75zaDklNO7MWhHYdGyD95w.png" /></figure><p>Ballerina’s philosophy is clear — <em>let developers focus on logic, not configuration.</em></p><h4>Real-World Use Case</h4><p>Imagine you’re running a <strong>payment microservice</strong> that handles transactions. With Ballerina, you can:</p><ul><li>Write your service logic</li><li>Annotate it for deployment</li><li>Automatically scale replicas during high traffic</li><li>Enable tracing for distributed debugging</li></ul><p>You can push updates, monitor health, and scale seamlessly — all with minimal operational overhead.</p><h4>Bonus: Integrating with CI/CD</h4><p>Ballerina integrates easily into <strong>Jenkins</strong>, <strong>GitHub Actions</strong>, or <strong>Azure DevOps pipelines</strong>.</p><p>Your pipeline can:</p><ol><li>Run bal build to compile and generate manifests.</li><li>Use kubectl or Helm to deploy automatically.</li><li>Include health checks and scaling policies for production.</li></ol><p>This ensures that your microservices are continuously delivered and automatically scalable across environments.</p><h4>Conclusion</h4><p>Ballerina takes the <strong>pain out of Kubernetes deployments</strong>. With just a few annotations, you can:</p><ul><li>Build, containerize, and deploy microservices</li><li>Scale effortlessly</li><li>Enable observability</li><li>Maintain clean, readable code without YAML sprawl</li></ul><p>Whether you’re building a simple API or a distributed enterprise system, <strong>Ballerina + Kubernetes</strong> provides a modern, streamlined, and developer-friendly way to scale in the cloud.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69158bc5d937" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observability Out of the Box: Tracing, Metrics, and Logs in Ballerina]]></title>
            <link>https://lasithmanaram.medium.com/observability-out-of-the-box-tracing-metrics-and-logs-in-ballerina-b191fa43a2d3?source=rss-be94a785d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b191fa43a2d3</guid>
            <category><![CDATA[data-observability]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <dc:creator><![CDATA[Lasith Jayalath]]></dc:creator>
            <pubDate>Thu, 30 Oct 2025 14:38:49 GMT</pubDate>
            <atom:updated>2025-10-30T14:38:49.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Vqv14_rodmHDIDga3ECbA.png" /></figure><p>In modern cloud-native systems, <strong>observability</strong> isn’t a luxury — it’s essential. Developers need visibility into how their applications behave in production: what requests are flowing through, where bottlenecks occur, and how failures propagate across services. Traditionally, achieving this level of insight meant setting up <strong>OpenTelemetry</strong>, <strong>Prometheus</strong>, and logging frameworks manually — an error-prone and configuration-heavy process.</p><p><strong>Ballerina</strong>, however, takes a radically different approach. Designed from the ground up for integration and observability, it offers <strong>built-in tracing, metrics, and logging</strong> — all powered by <strong>OpenTelemetry</strong>. This article dives into how Ballerina simplifies observability and how it compares to manual setups in Node.js and Go.</p><h4>1. The Challenge of Manual Observability</h4><p>In most languages, enabling observability means integrating several components:</p><ul><li>Installing OpenTelemetry SDKs for tracing</li><li>Configuring exporters for Jaeger or Zipkin</li><li>Integrating Prometheus for metrics</li><li>Propagating trace context manually between microservices</li><li>Configuring structured logging to correlate events</li></ul><p>While frameworks like Express.js or Gin make service creation easy, observability still requires extensive boilerplate and external configuration.</p><h4>2. Ballerina’s Built-In Observability</h4><p>Ballerina flips this paradigm by <strong>baking observability directly into the runtime</strong>. The language provides <strong>native support for OpenTelemetry</strong>, enabling tracing, metrics, and logs without any third-party libraries.</p><p>Key features include:</p><ul><li><strong>Automatic tracing</strong> for HTTP, gRPC, database, and other connectors</li><li><strong>Metrics collection</strong> out of the box (Prometheus format)</li><li><strong>Structured logs</strong> automatically correlated with trace and span IDs</li><li><strong>Simple configuration</strong> — just toggle observability on in a .toml file</li></ul><p>Ballerina’s philosophy: <em>“Observability should not be an afterthought.”</em></p><h4>3. Enabling Observability in Ballerina</h4><p>Let’s start with a simple service:</p><pre>import ballerina/http;<br><br>service /hello on new http:Listener(8080) {<br>    resource function get sayHi() returns string {<br>        return &quot;Hello, World!&quot;;<br>    }<br>}</pre><p>To enable observability, add the following to your Config.toml:</p><pre>[ballerina.observe]<br>enabled = true<br>metricsEnabled = true<br>tracingEnabled = true</pre><p>That’s it. No external dependencies, no manual setup.</p><p>Once the service runs, Ballerina automatically:</p><ul><li>Exposes Prometheus metrics at /metrics</li><li>Sends traces to Jaeger or Zipkin (if configured)</li><li>Logs all requests with trace correlation</li></ul><h4>4. Tracing Made Effortless</h4><p>Every Ballerina service and client call generates a <strong>trace</strong> automatically. When this service makes a downstream HTTP or database call, the <strong>trace context</strong> is propagated automatically, allowing end-to-end visibility.</p><p>You can visualize this in <strong>Jaeger</strong>:</p><ul><li>Root span: /hello/sayHi</li><li>Child spans: database queries, connector calls, etc.</li><li>Metadata: latency, HTTP status, module info</li></ul><p>This level of visibility usually requires several SDK integrations in Node.js or Go — but in Ballerina, it’s built in.</p><h4>5. Metrics with No Extra Setup</h4><p>Metrics are crucial for tracking the health of a system. Ballerina emits <strong>default metrics</strong> automatically, including:</p><ul><li>http_requests_total – number of HTTP requests handled</li><li>http_request_duration_seconds – latency of requests</li><li>http_errors_total – total failed requests</li></ul><p>You can view them directly through Prometheus or Grafana dashboards.</p><p>Example metric output:</p><pre># HELP http_requests_total Total number of HTTP requests<br># TYPE http_requests_total counter<br>http_requests_total{method=&quot;GET&quot;,service=&quot;/hello&quot;} 24</pre><h4>6. Logging with Context</h4><p>Logs are more powerful when correlated with traces. Ballerina’s runtime automatically appends <strong>trace IDs</strong> and <strong>span IDs</strong> to logs, allowing developers to connect logs to specific traces easily.</p><p>Example log:</p><pre>time = 2025-10-30T12:05:33Z level=INFO module=hello<br>message=&quot;Request completed&quot;<br>traceId=abcd1234 spanId=ef56</pre><p>In contrast, achieving this in Node.js or Go typically requires middleware and manual context management.</p><h4>7. Comparing Ballerina with Node.js and Go</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*vH1ms2EQRJEXDLM6TnO89w.png" /></figure><p>This native integration gives Ballerina developers a head start in production readiness — fewer moving parts, fewer configuration errors.</p><h4>8. Creating Custom Metrics and Spans</h4><p>While automatic instrumentation covers most use cases, Ballerina also allows developers to define <strong>custom observability data</strong>.</p><p>Example custom counter:</p><pre>import ballerina/observe;<br><br>observe:Counter counter = new (&quot;my_app&quot;, &quot;requests_total&quot;, &quot;Total requests received&quot;);<br><br>function recordRequest() {<br>    counter.increment();<br>}</pre><p>This integrates seamlessly with the built-in observability pipeline — no extra configuration needed.</p><h4>9. Why This Matters</h4><p>In microservice environments, diagnosing latency or failure issues across distributed systems can be challenging. Ballerina’s <strong>first-class observability</strong> support ensures that developers:</p><ul><li>Spend less time setting up and more time analyzing</li><li>Get consistent, reliable metrics and traces</li><li>Have full visibility into runtime behavior out of the box</li></ul><p>It’s observability done <em>by design</em>, not by integration.</p><h4>10. Conclusion</h4><p>Ballerina’s built-in observability represents a new standard for developer productivity and system transparency. Instead of wiring up telemetry manually, developers can focus on business logic while Ballerina automatically provides <strong>end-to-end visibility</strong>.</p><p>Whether you’re building APIs, integrations, or event-driven systems — Ballerina ensures your code is <strong>observable by default</strong>, ready for production without extra effort.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b191fa43a2d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From REST to GraphQL: Building Modern APIs in Ballerina]]></title>
            <link>https://lasithmanaram.medium.com/from-rest-to-graphql-building-modern-apis-in-ballerina-9e2c4d1702b3?source=rss-be94a785d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e2c4d1702b3</guid>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Lasith Jayalath]]></dc:creator>
            <pubDate>Thu, 30 Oct 2025 13:05:55 GMT</pubDate>
            <atom:updated>2025-10-30T13:05:55.535Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Ballerina’s flexible service design supports both REST and GraphQL — ideal for evolving modern APIs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axIyrj3Bi2OwG0Yze72jRg.png" /></figure><p>In the ever-evolving landscape of API development, REST and GraphQL have emerged as two dominant paradigms. REST has been the industry standard for over a decade, emphasizing simplicity and resource-based design. GraphQL, on the other hand, has gained traction for its flexibility and efficiency in data fetching.</p><p>For organizations modernizing their integration architectures, switching entirely from REST to GraphQL is rarely immediate — it’s often a gradual evolution. This is where <strong>Ballerina</strong>, a language designed specifically for integration and networked applications, shines. Ballerina’s service design model allows developers to build, expose, and evolve APIs seamlessly — supporting both REST and GraphQL natively within the same language ecosystem.</p><h4>The Need for Flexible API Design</h4><p>Modern systems demand APIs that can adapt quickly to business and consumer needs. RESTful APIs provide a predictable structure — ideal for CRUD-style operations and stable integrations. However, as frontend applications evolve (especially in mobile and web), REST can become too rigid:</p><ul><li>Clients may over-fetch or under-fetch data.</li><li>Multiple endpoints may be needed for a single screen.</li><li>Versioning becomes cumbersome as new requirements emerge.</li></ul><p><strong>GraphQL</strong> solves these pain points by allowing clients to specify exactly what data they need. Instead of maintaining multiple endpoints, developers can define a single GraphQL schema with resolvers mapping to underlying services.</p><p>Yet, many systems already have established REST backends. Rewriting everything in GraphQL isn’t practical — what’s needed is a <strong>coexistence strategy</strong>, and that’s where <strong>Ballerina’s unified approach</strong> comes in.</p><h4>Ballerina’s Unified Service Model</h4><p>Ballerina treats <strong>network services</strong> as first-class citizens in the language. Both REST and GraphQL are not external frameworks but <strong>built into the language runtime</strong>. This makes API design more intuitive, strongly typed, and easier to maintain.</p><p>At its core, Ballerina defines services using listeners and resources — the same concept powers both REST and GraphQL implementations.</p><h4>A REST Example</h4><pre>import ballerina/http;<br><br>service /users on new http:Listener(8080) {<br><br>    resource function get .() returns json {<br>        return [<br>            { id: 1, name: &quot;Alice&quot; },<br>            { id: 2, name: &quot;Bob&quot; }<br>        ];<br>    }<br><br>    resource function get [int id]() returns json {<br>        return { id, name: &quot;User &quot; + id.toString() };<br>    }<br>}</pre><p>Here, each resource function maps naturally to HTTP methods (get, post, etc.) and URI templates. The design is declarative, type-safe, and fully aligned with REST principles.</p><h4>Adding GraphQL to the Mix</h4><p>Ballerina extends this same service abstraction to GraphQL — but instead of endpoints, it exposes a <strong>schema-based API</strong>.</p><h4>A GraphQL Example</h4><pre>import ballerina/graphql;<br><br>service /graphql on new graphql:Listener(9090) {<br><br>    resource function get users() returns User[] {<br>        return [<br>            { id: 1, name: &quot;Alice&quot; },<br>            { id: 2, name: &quot;Bob&quot; }<br>        ];<br>    }<br><br>    resource function get user(int id) returns User {<br>        return { id, name: &quot;User &quot; + id.toString() };<br>    }<br>}<br><br>type User record {<br>    int id;<br>    string name;<br>};</pre><p>This GraphQL service defines queries for users and user, mirroring the REST example — but now, the client decides what fields to fetch, reducing over-fetching and enabling flexible queries.</p><h4>Why Ballerina Excels at API Evolution</h4><p>Ballerina’s language design inherently supports <strong>evolution from REST to GraphQL</strong> in a clean, maintainable way.</p><p>Here’s why:</p><h4>1. Unified Programming Model</h4><p>Ballerina doesn’t force developers to use different frameworks or DSLs. Both REST and GraphQL share the same service abstraction, enabling you to refactor or layer them side-by-side. You can even <strong>reuse data models and business logic</strong> across both APIs.</p><h4>2. Built-in Type Safety</h4><p>Ballerina’s strong, structural type system ensures compile-time validation between JSON, GraphQL types, and service responses. This reduces runtime type mismatches — a common issue in dynamic frameworks like Node.js.</p><h4>3. Seamless Interoperability</h4><p>Because Ballerina supports multiple protocol listeners (HTTP, GraphQL, gRPC, WebSocket, etc.), developers can run <strong>hybrid services</strong> that expose REST and GraphQL simultaneously — allowing gradual migration.</p><h4>4. Declarative and Observable by Design</h4><p>Ballerina’s observability features — metrics, logs, and tracing — are built-in. Whether you’re serving REST or GraphQL, you can monitor latency, request counts, and payloads consistently across both API styles.</p><h4>5. Easy Transition Path</h4><p>Organizations can start with REST services and introduce a GraphQL layer using the same backend logic:</p><ul><li>Step 1: Expose existing REST endpoints.</li><li>Step 2: Introduce a GraphQL service referencing the same resource functions.</li><li>Step 3: Gradually transition consumers to GraphQL queries without breaking existing REST clients.</li></ul><h3>Bringing It Together — A Hybrid API Example</h3><p>Here’s how Ballerina makes REST and GraphQL coexist seamlessly:</p><pre>import ballerina/http;<br>import ballerina/graphql;<br><br>type User record {|<br>    int id;<br>    string name;<br>|};<br><br>// Common business logic<br>function getAllUsers() returns User[] {<br>    return [<br>        { id: 1, name: &quot;Alice&quot; },<br>        { id: 2, name: &quot;Bob&quot; }<br>    ];<br>}<br><br>// REST endpoint<br>service /users on new http:Listener(8080) {<br>    resource function get .() returns User[] {<br>        return getAllUsers();<br>    }<br>}<br><br>// GraphQL endpoint<br>service /graphql on new graphql:Listener(9090) {<br>    resource function get users() returns User[] {<br>        return getAllUsers();<br>    }<br>}</pre><p>This dual-service setup allows you to maintain <strong>API stability</strong> (REST) while introducing <strong>flexible query capabilities</strong> (GraphQL) — all from the same source logic.</p><h4>Conclusion</h4><p>Ballerina is more than just another programming language — it’s an integration-first platform built to evolve with modern API needs.<br> Its <strong>native support for both REST and GraphQL</strong>, backed by a <strong>strong type system</strong>, <strong>declarative syntax</strong>, and <strong>observability</strong>, makes it the ideal choice for teams modernizing their API stack.</p><p>As organizations move toward composable architectures and dynamic frontends, the ability to evolve from REST to GraphQL — <em>without re-engineering the entire system</em> — is a strategic advantage.</p><p>With Ballerina, that transition is not just possible — it’s natural.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e2c4d1702b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Ballerina’s Concurrency Model: Workers, Strands, and Structured Concurrency]]></title>
            <link>https://lasithmanaram.medium.com/inside-ballerinas-concurrency-model-workers-strands-and-structured-concurrency-55ea2b8ce2e0?source=rss-be94a785d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/55ea2b8ce2e0</guid>
            <category><![CDATA[concurrency-model]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <dc:creator><![CDATA[Lasith Jayalath]]></dc:creator>
            <pubDate>Wed, 29 Oct 2025 16:47:55 GMT</pubDate>
            <atom:updated>2025-10-29T16:47:55.648Z</atom:updated>
            <content:encoded><![CDATA[<h3>inaInside Ballerina’s Concurrency Model: Workers, Strands, and Structured Concurrency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDvv_GgGqrVoJMZsJw92xg.png" /></figure><p>Modern software systems increasingly rely on concurrency — whether it’s handling multiple API requests, integrating services, or processing data streams. Yet, concurrency models in popular languages like Go’s goroutines or JavaScript’s async/await often come with pitfalls: unstructured execution, hidden race conditions, and tricky synchronization.</p><p><strong>Ballerina</strong>, a cloud-native programming language, rethinks concurrency with a design that’s both powerful and safe. Its <strong>structured concurrency</strong>, <strong>workers</strong>, and <strong>strands</strong> enable developers to write concurrent code that’s deterministic, maintainable, and resilient.</p><p>This article explores how Ballerina’s concurrency model works, how it differs from traditional models, and why it’s a game changer for integration and network-driven applications.</p><h4>1. The Need for Safer Concurrency</h4><p>Concurrency is essential — but difficult to manage.</p><ul><li><strong>In Go</strong>, goroutines are lightweight but <em>unstructured</em> — they can spawn freely without a clear lifecycle, leading to “goroutine leaks” or unjoined routines.</li><li><strong>In JavaScript or Python</strong>, async/await simplifies asynchronous programming, but lacks strong concurrency composition. Tasks often run independently with minimal control over lifetimes or cancellation.</li></ul><p>Ballerina takes a different route: it <strong>bakes structured concurrency into the language design</strong>, ensuring that concurrent tasks always have a clear scope and lifecycle.</p><h4>2. The Building Blocks: Workers and Strands</h4><h4>Workers — Concurrency Within Functions</h4><p>In Ballerina, concurrency starts at the function level with <strong>workers</strong>.<br> A function can have multiple workers that execute concurrently, communicating through <strong>message passing</strong> (channels).</p><p>Example:</p><pre>function processData() returns string {<br>    worker A {<br>        string resultA = &quot;Data from worker A&quot;;<br>        resultA -&gt; worker B;<br>    }<br>    worker B {<br>        string msg = &lt;- worker A;<br>        return msg + &quot; processed by worker B&quot;;<br>    }<br>}</pre><p><strong>What’s happening here:</strong></p><ul><li>worker A and worker B run <em>concurrently</em> within the same function.</li><li>They communicate safely through message passing (-&gt; and &lt;-).</li><li>The Ballerina runtime ensures deterministic ordering and no shared mutable state.</li></ul><p>This design eliminates many common concurrency bugs like race conditions and deadlocks.</p><h4>Strands — The Lightweight Threads of Ballerina</h4><p>At a lower level, <strong>strands</strong> are the lightweight execution units managed by the Ballerina runtime.</p><p>Think of strands as Ballerina’s equivalent to goroutines — but with <strong>structured control and safety guarantees</strong>.</p><p>Every worker runs on a separate strand. The runtime manages scheduling and execution efficiently, allowing thousands of strands to run concurrently on a few OS threads.</p><p>Example with start and wait keywords:</p><pre>function main() returns error? {<br>    future&lt;string&gt; f1 = start fetchData(&quot;user&quot;);<br>    future&lt;string&gt; f2 = start fetchData(&quot;order&quot;);<br><br>    string user = wait f1;<br>    string order = wait f2;<br>    io:println(&quot;Fetched:&quot;, user, &quot;and&quot;, order);<br>}</pre><p>Here:</p><ul><li>start launches a new <strong>strand</strong> concurrently.</li><li>wait suspends until the result is available.</li><li>The runtime ensures both strands complete safely, even if one fails.</li></ul><h4>3. Structured Concurrency — The Secret Ingredient</h4><p>Ballerina enforces <strong>structured concurrency</strong>, meaning:</p><ul><li>All concurrent operations must exist within a well-defined scope.</li><li>When the scope exits, all concurrent strands within it are joined, canceled, or awaited.</li><li>No “dangling” concurrent tasks can outlive their parent function.</li></ul><p>For instance:</p><pre>function handleRequest() returns error? {<br>    future f = start computeResponse();<br>    // If an error occurs or the function returns early, the runtime ensures cleanup<br>    check doSomethingElse();<br>    wait f; // join before exiting<br>}</pre><p>If doSomethingElse() fails, the runtime cancels the concurrent computeResponse() task — ensuring <strong>no leaks or orphaned strands</strong>.</p><p>This is fundamentally different from Go or JavaScript, where concurrent tasks can easily outlive their parent function unless explicitly handled.</p><h4>4. Safer Communication via Message Passing</h4><p>Ballerina disallows shared mutable memory between workers.<br> Instead, it uses <strong>value semantics</strong> and <strong>message passing</strong> — ensuring data immutability once shared.</p><p>This eliminates a whole class of bugs that plague multi-threaded applications:</p><ul><li>No data races</li><li>No inconsistent states</li><li>No manual locking required</li></ul><p>This approach borrows from the <strong>actor model</strong> but keeps it lightweight and native to the language.</p><h4>5. Concurrency Composition with wait and checkpanic</h4><p>Ballerina’s concurrency model also offers elegant composition patterns:</p><ul><li><strong>wait</strong> can handle multiple futures together:</li></ul><pre>var [res1, res2] = wait {f1, f2};</pre><ul><li>If either future fails, the error is propagated automatically.</li><li><strong>checkpanic</strong> ensures errors in concurrent tasks are caught and managed deterministically — improving fault tolerance in distributed systems.</li></ul><h4>6. Why It’s Better Than Goroutines or Async/Await</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*K-hU15zuUMtbyjGtsZkkBw.png" /></figure><p><strong>Result:</strong> Ballerina’s approach leads to <strong>cleaner, safer, and more predictable concurrent programs</strong>, especially in <strong>integration-heavy or distributed systems</strong>.</p><h4><strong>7. Real-World Example — Concurrent Service Calls</strong></h4><p>In API integration scenarios, parallel service calls are common.<br> Here’s how clean it looks in Ballerina:</p><pre>function getUserData() returns error? {<br>    future&lt;string&gt; fProfile = start fetchProfile();<br>    future&lt;string&gt; fOrders = start fetchOrders();<br><br>    var [profile, orders] = wait {fProfile, fOrders};<br>    io:println(&quot;Profile:&quot;, profile);<br>    io:println(&quot;Orders:&quot;, orders);<br>}</pre><p>The code:</p><ul><li>Runs both requests concurrently.</li><li>Waits for both results.</li><li>Automatically propagates errors or cancellations.</li></ul><p>No complex callbacks, no race conditions, no goroutine leaks — just safe and readable concurrency.</p><h4>8. Conclusion</h4><p>Ballerina’s concurrency model redefines how developers approach concurrent programming.<br> By combining <strong>workers</strong>, <strong>strands</strong>, and <strong>structured concurrency</strong>, it provides:</p><ul><li>Safer and more predictable concurrency.</li><li>Built-in error and cancellation handling.</li><li>Clear scoping and lifecycle management.</li></ul><p>In contrast to unstructured models like goroutines or async/await, Ballerina offers a <strong>well-structured, integration-friendly concurrency framework</strong> that aligns perfectly with the needs of modern, cloud-native software.</p><blockquote><strong><em>In short:</em></strong><em> Ballerina doesn’t just let you write concurrent programs — it ensures they’re correct by design.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55ea2b8ce2e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Future of Integration: Why Ballerina Could Replace ESBs]]></title>
            <link>https://lasithmanaram.medium.com/the-future-of-integration-why-ballerina-could-replace-esbs-7b09c334597b?source=rss-be94a785d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b09c334597b</guid>
            <category><![CDATA[esb-vs-ballerina]]></category>
            <category><![CDATA[future-of-esb]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[esb]]></category>
            <dc:creator><![CDATA[Lasith Jayalath]]></dc:creator>
            <pubDate>Wed, 29 Oct 2025 01:17:22 GMT</pubDate>
            <atom:updated>2025-10-29T01:17:22.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3FxEJYPPBszmS1N0ES7GQ.png" /></figure><h3>Introduction</h3><p>For decades, <strong>Enterprise Service Buses (ESBs)</strong> have been the backbone of enterprise integration. They orchestrated communication between heterogeneous systems, offering centralized control, mediation, and transformation capabilities. However, as organizations move toward <strong>cloud-native</strong>, <strong>microservice-based</strong>, and <strong>event-driven</strong> architectures, traditional ESBs are starting to show their age.</p><p>Enter <strong>Ballerina</strong> — a <strong>cloud-native, code-first integration language</strong> that reimagines what enterprise integration can be. Instead of heavyweight middleware, Ballerina brings integration directly into the code, empowering developers to write, deploy, and maintain integrations as lightweight, version-controlled, and container-ready services.</p><h3>1. The Limitations of Traditional ESBs</h3><p>In their prime, ESBs like <strong>Mule ESB</strong>, <strong>WSO2 ESB</strong>, and <strong>IBM Integration Bus</strong> offered valuable abstractions for system interoperability. Yet, as integration patterns evolved, these traditional ESBs began facing challenges:</p><ul><li><strong>Heavyweight Infrastructure:</strong> Most ESBs require centralized runtime environments, message brokers, and governance layers that are difficult to scale elastically.</li><li><strong>Operational Complexity:</strong> Managing clustered ESB servers, message queues, and mediation flows adds overhead — both for operations and development teams.</li><li><strong>Slower Development Cycles:</strong> Integration logic often lives in visual tools or configuration XMLs, making CI/CD pipelines harder to maintain.</li><li><strong>Limited Cloud Readiness:</strong> ESBs were designed for data centers, not dynamic cloud or Kubernetes environments.</li></ul><p>These challenges have led many organizations to seek <strong>lightweight, developer-centric alternatives</strong> — and that’s where Ballerina shines.</p><h3>2. Ballerina: Integration Reimagined</h3><p><strong>Ballerina</strong>, developed by <strong>WSO2</strong>, is a <strong>programming language purpose-built for integration</strong> in the modern cloud era. It’s not a library or middleware — it’s a language where integration is a <strong>first-class citizen</strong>.</p><p>Key design principles include:</p><ul><li><strong>Network Awareness Built-In:</strong> Ballerina treats services, endpoints, and network interactions as native language constructs.</li><li><strong>Cloud-Native by Design:</strong> Supports Docker, Kubernetes, and distributed tracing out-of-the-box.</li><li><strong>Code-First, Not Config-First:</strong> Integrations are written as code, with clear syntax and structure — no XML, no hidden configurations.</li><li><strong>Observability and Resilience:</strong> Built-in metrics, tracing, and error-handling make it production-ready for modern architectures.</li></ul><h3>3. From Centralized ESBs to Decentralized Integration</h3><p>In a traditional ESB setup, integration logic is <strong>centralized</strong> — all services communicate through a single integration hub. While this simplifies monitoring and control, it also creates a <strong>single point of failure</strong> and limits scalability.</p><p>Ballerina promotes a <strong>decentralized, microservice-oriented</strong> approach:</p><ul><li>Each microservice can own its own integration logic.</li><li>Integration flows can be versioned, tested, and deployed independently.</li><li>Developers gain full visibility and control over the integration code.</li></ul><p>In essence, Ballerina breaks the “bus” into a network of lightweight, independent <strong>integration microservices</strong> — perfectly aligned with modern <strong>DevOps</strong> and <strong>CI/CD pipelines</strong>.</p><h3>4. Code-First Integration in Action</h3><p>Let’s consider a simple example: consuming an API, transforming data, and sending it to another endpoint.</p><p>In Ballerina, it’s just a few lines of code:</p><pre>import ballerina/http;<br><br>service / on new http:Listener(8080) {<br>    resource function post transform(http:Caller caller, http:Request req) returns error? {<br>        json input = check req.getJsonPayload();<br>        json transformed = { name: input.name.toUpperCase(), timestamp: time:currentTime() };<br>        check caller-&gt;respond(transformed);<br>    }<br>}</pre><p>This snippet:</p><ul><li>Defines an HTTP service.</li><li>Processes an incoming JSON payload.</li><li>Applies transformation logic.</li><li>Sends the response — all in a <strong>single, readable, version-controlled</strong> unit.</li></ul><p>Compare that to ESB-based XML configurations — and the advantage becomes obvious.</p><h3>5. Built for the Cloud and Beyond</h3><p>Modern integration solutions must be <strong>Kubernetes-native</strong>, <strong>serverless-friendly</strong>, and <strong>observable by default</strong>. Ballerina was built with these in mind:</p><ul><li><strong>Docker and Kubernetes Support:</strong> Every Ballerina service can be packaged and deployed with minimal effort.</li><li><strong>Native Observability:</strong> Built-in Prometheus, OpenTelemetry, and Jaeger integration.</li><li><strong>Resilience Patterns:</strong> Built-in support for circuit breakers, retries, and timeouts — no third-party dependency required.</li></ul><p>In short, Ballerina bridges the gap between <strong>integration developer</strong> and <strong>cloud engineer</strong>.</p><h3>6. The Developer Advantage</h3><p>Unlike ESBs that separate integration logic from code, Ballerina puts developers in full control:</p><ul><li>Full IDE support (VS Code plugin).</li><li>Built-in visual representation of code (sequence diagrams generated automatically).</li><li>Easy debugging and testing using bal test and bal run.</li><li>GitOps-friendly — integration code is versioned like any other service.</li></ul><p>This eliminates the long-standing tension between <strong>integration teams</strong> and <strong>application developers</strong> — everyone now speaks the same language: <strong>code</strong>.</p><h3>7. Why Ballerina Could Replace ESBs</h3><p>Let’s summarize the shift:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syPIZe3xigDhN0K9l3KMlg.jpeg" /></figure><p>The trend is clear — integration is no longer about middleware; it’s about <strong>distributed, programmable connectivity</strong>.</p><h3>Conclusion: Integration Without the Bus</h3><p>The <strong>future of integration</strong> won’t revolve around a monolithic bus. It will be built on <strong>small, composable, code-driven services</strong> that can evolve with the speed of modern software delivery.</p><p><strong>Ballerina</strong> embodies this future — a language that merges the power of APIs, services, and event-driven communication into one cohesive, developer-friendly model.</p><p>As enterprises modernize their integration stacks, <strong>Ballerina isn’t just an alternative to ESBs — it’s the natural evolution</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b09c334597b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ballerina’s Type System: Why Strong Typing Matters in API Design]]></title>
            <link>https://lasithmanaram.medium.com/ballerinas-type-system-why-strong-typing-matters-in-api-design-7fb82ac59358?source=rss-be94a785d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fb82ac59358</guid>
            <category><![CDATA[type-systems]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[api-design]]></category>
            <dc:creator><![CDATA[Lasith Jayalath]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 19:37:54 GMT</pubDate>
            <atom:updated>2025-10-28T19:37:54.974Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9SQwY61rXECdTHSI_Q8rA.png" /></figure><p>APIs are the backbone of modern applications — from microservices and AI integrations to real-time analytics. Yet, one of the biggest headaches developers face is <strong>runtime errors</strong> due to inconsistent or malformed data structures.</p><p>Languages like JavaScript or Python allow rapid API development, but their <strong>weak typing</strong> often leads to bugs surfacing only during execution. Enter <strong>Ballerina</strong>, a language purpose-built for networked and cloud-native systems — where <strong>strong typing</strong> meets <strong>API-first design</strong>.</p><p>This article explores how <strong>Ballerina’s type system</strong> and <strong>automatic JSON-to-type binding</strong> make API integration safer, more reliable, and developer-friendly.</p><h3>Why Type Safety Matters in API Design</h3><p>Let’s start with a simple truth — most API failures are <strong>not because the API is unreachable</strong>, but because:</p><ul><li>The <strong>response shape changed</strong>.</li><li>A <strong>field was missing or renamed</strong>.</li><li>The <strong>expected type didn’t match</strong> (e.g., string instead of number).</li><li>Or, someone <strong>forgot to validate the input</strong>.</li></ul><p>In dynamic languages, these errors surface only when you hit the endpoint at runtime. But in strongly typed systems like Ballerina, the compiler itself guards you from these issues.</p><h3>Strong Typing = Predictable APIs</h3><p>In Ballerina:</p><ul><li>Types represent <strong>contracts</strong> between systems.</li><li>The compiler ensures your request and response structures <strong>match exactly</strong> what the API expects.</li><li>Mismatches are caught <strong>at compile time</strong>, not in production.</li></ul><h3>JSON-to-Type Binding — The Game Changer</h3><p>One of Ballerina’s most powerful features is <strong>automatic JSON-to-type binding</strong>.</p><p>This means that when your API returns JSON, Ballerina can <strong>automatically map it</strong> into a typed record structure — safely and efficiently.</p><p>Let’s explore a small example.</p><h3>Example: Typing an API Response</h3><p>Imagine you’re consuming a public API that returns user data like this:</p><pre>{<br>  &quot;id&quot;: 101,<br>  &quot;name&quot;: &quot;Alice&quot;,<br>  &quot;email&quot;: &quot;alice@example.com&quot;,<br>  &quot;verified&quot;: true<br>}</pre><p>In a typical language like JavaScript, you’d parse this JSON and hope the keys exist:</p><pre>const user = JSON.parse(response);<br>console.log(user.email); // Works... unless it&#39;s missing</pre><p>But in <strong>Ballerina</strong>, we define the data contract as a record type:</p><pre>type User record {<br>    int id;<br>    string name;<br>    string email;<br>    boolean verified;<br>};</pre><p>Now, let’s consume the API safely:</p><pre>import ballerina/http;<br>import ballerina/log;<br><br>service /users on new http:Listener(8080) {<br><br>    resource function get info() returns User|error {<br>        http:Client client = check new (&quot;https://jsonplaceholder.typicode.com&quot;);<br><br>        http:Response response = check client-&gt;get(&quot;/users/1&quot;);<br>        json jsonPayload = check response.getJsonPayload();<br><br>        // Convert JSON → Typed record<br>        User user = check jsonPayload.cloneWithType(User);<br><br>        return user;<br>    }<br>}</pre><p><strong>What happens here:</strong></p><ul><li>The cloneWithType(User) ensures every field matches the User record.</li><li>If a field is missing or of the wrong type — <strong>the compiler throws an error</strong>.</li><li>Your runtime remains safe from unexpected structure mismatches.</li></ul><h3>Compile-Time Guarantees</h3><p>Here’s what happens when something doesn’t match:</p><p>Let’s say the API suddenly changes the field “verified” to “isVerified”.</p><p>In JavaScript or Python — you’ll only notice at runtime.</p><p>In Ballerina — you’ll see an immediate compile-time type error like:</p><pre>incompatible types: expected &#39;boolean&#39;, found &#39;json&#39;</pre><p>This gives you <strong>early feedback</strong>, reducing debugging time and production issues.</p><h3>JSON-to-Type Conversion in the Other Direction</h3><p>It works both ways! When sending JSON to APIs, your typed data structures ensure that <strong>only valid fields</strong> go out.</p><p>For instance:</p><pre>User newUser = {<br>    id: 102,<br>    name: &quot;Bob&quot;,<br>    email: &quot;bob@example.com&quot;,<br>    verified: false<br>};<br><br>json requestPayload = &lt;json&gt;newUser; // Safe conversion<br>check client-&gt;post(&quot;/users&quot;, requestPayload);</pre><p>Here, Ballerina guarantees that:</p><ul><li>All required fields are present.</li><li>The field types match.</li><li>Optional or extra fields are excluded.</li></ul><p>No more malformed payloads — ever.</p><h3>Why This Matters for Integration Engineers</h3><p>In integration-heavy projects — like healthcare systems, finance platforms, or AI gateways — <strong>data consistency</strong> is critical.</p><p>A single malformed field can break an entire workflow.</p><p>Ballerina’s <strong>type system</strong> eliminates these surprises by:</p><ul><li>Making <strong>data models first-class citizens</strong>.</li><li>Providing <strong>compile-time validation</strong> of payloads.</li><li>Supporting <strong>OpenAPI-to-type generation</strong>, so your types always match the latest API spec.</li></ul><h3>OpenAPI Integration</h3><p>Ballerina can even <strong>generate typed clients directly from OpenAPI definitions</strong>:</p><pre>bal openapi -i openapi.yaml -o generated/</pre><p>This creates all the records, clients, and functions — each strongly typed and fully documented.</p><p>You just import the generated package and call the methods — <strong>no manual JSON parsing needed</strong>.</p><p>This feature alone positions Ballerina as a <strong>“contract-first” language</strong> for the cloud-native era.</p><h3>Why Strong Typing is the Future of APIs</h3><p>Here’s the bigger picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJ1n07Uh7f3_XhRwrkxMgw.jpeg" /></figure><p>Strong typing doesn’t slow you down — it <strong>saves you</strong> from debugging days later.</p><p>Ballerina takes the best of both worlds:</p><p>the <strong>flexibility of JSON</strong> and the <strong>safety of typed data</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fb82ac59358" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Microservices: Ballerina vs Node.js — Developer Experience Showdown]]></title>
            <link>https://lasithmanaram.medium.com/building-microservices-ballerina-vs-node-js-developer-experience-showdown-5fd1e462695c?source=rss-be94a785d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fd1e462695c</guid>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Lasith Jayalath]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 19:46:18 GMT</pubDate>
            <atom:updated>2025-10-25T19:46:18.367Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Microservices: Ballerina vs Node.js — Developer Experience Showdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgJ40XAFw7CUnrku3k95tQ.png" /></figure><h3>Introduction</h3><p>Microservices have revolutionized how we build modern cloud applications — small, independent services communicating through APIs, enabling faster development and scalability.</p><p>However, as any backend engineer knows, the <em>real challenge</em> is not just building microservices , it’s about <strong>how easy, safe, and efficient</strong> it is to build and maintain them.</p><p>In this showdown, we’ll compare two fascinating players from different generations:</p><ul><li><strong>Node.js</strong>, the veteran loved by millions of JavaScript developers for building fast, event-driven APIs.</li><li><strong>Ballerina</strong>, a new cloud-native language designed by <strong>WSO2</strong>, purpose-built for integration, APIs, and observability in the cloud era.</li></ul><p>Let’s see how they stack up when it comes to <strong>developer experience, observability, and microservice development</strong>.</p><h4>1. Getting Started: Ease of Setup</h4><h4>Ballerina</h4><p>Ballerina is designed for developers who want to start small and move fast, it comes with everything built in.</p><p>No npm, no dependency juggling — just write, run, and observe.</p><p><strong>Example: Hello World Microservice</strong></p><pre>import ballerina/http;<br><br>service /hello on new http:Listener(9090) {<br>    resource function get greet() returns string {<br>        return &quot;Hello from Ballerina!&quot;;<br>    }<br>}</pre><p>To run:</p><pre>bal run</pre><p>That’s it! The service runs immediately.</p><p>To deploy to the cloud, just execute:</p><pre>bal build --cloud=docker</pre><p>It will generate a ready-to-run Docker image.</p><h4>Node.js</h4><p>Node.js, powered by JavaScript, is flexible and well-known. You’ll need to set up your project manually.</p><p><strong>Example: Hello World in Express.js</strong></p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br><br>app.get(&#39;/hello&#39;, (req, res) =&gt; {<br>    res.send(&#39;Hello from Node.js!&#39;);<br>});<br><br>app.listen(9090, () =&gt; console.log(&#39;Server running on port 9090&#39;));</pre><p>Steps:</p><pre>npm init -y<br>npm install express<br>node index.js</pre><p><strong>Verdict:</strong></p><p>Ballerina provides a <strong>minimal setup</strong> — it’s “ready for APIs” out of the box.</p><p>Node.js gives you <strong>more flexibility</strong> but requires more setup steps and dependencies.</p><h3>2. Observability &amp; Cloud-Native Features</h3><p>Modern microservices need visibility — metrics, tracing, and logging.</p><p>Let’s see how these two handle it.</p><h4>Ballerina</h4><p>Observability is <strong>built-in by design</strong>.</p><ul><li>Native support for <strong>tracing, metrics, and logs</strong>.</li><li>Compatible with <strong>OpenTelemetry</strong> and <strong>Prometheus</strong>.</li><li>Every service can be observed with no external libraries.</li></ul><p>You can enable observability with a single command:</p><pre>bal run --observability-included</pre><h4>Node.js</h4><p>Node.js requires <strong>third-party libraries</strong> to achieve the same:</p><ul><li>winston for logging</li><li>prom-client for metrics</li><li>opentelemetry-js for tracing</li></ul><p>Each library needs configuration and integration.</p><p><strong>Verdict:</strong></p><p>Ballerina wins for <strong>out-of-the-box observability</strong>, perfect for production environments.</p><h3>3. Type Safety &amp; Data Modeling</h3><h4>Ballerina</h4><p>Ballerina shines with <strong>strong typing</strong> and <strong>JSON integration</strong>.</p><p>You can map JSON data directly to typed records, ensuring data safety at compile time.</p><p><strong>Example:</strong></p><pre>type User record {<br>    string name;<br>    int age;<br>};<br><br>service /user on new http:Listener(9090) {<br>    resource function post addUser(@http:Payload User user) returns string {<br>        return &quot;User: &quot; + user.name + &quot; is &quot; + user.age.toString() + &quot; years old.&quot;;<br>    }<br>}</pre><p>If you send malformed data, the compiler or runtime will immediately flag it.</p><h4>Node.js</h4><p>JavaScript is <strong>dynamically typed</strong>, meaning data errors are caught only at runtime.</p><p>You can improve type safety using <strong>TypeScript</strong>, but it adds setup and tooling complexity.</p><p><strong>Verdict:</strong></p><p>Ballerina enforces <strong>type safety by default</strong>, ensuring reliable and predictable APIs.</p><h3>4. Integration and API-First Development</h3><h4>Ballerina</h4><p>Ballerina was <strong>born for integration</strong>. It supports:</p><ul><li>HTTP, gRPC, GraphQL</li><li>Kafka, NATS, WebSocket</li><li>OpenAPI (generate clients and stubs easily)</li></ul><p><strong>Example:</strong> You can auto-generate OpenAPI documentation:</p><pre>bal openapi</pre><p>Or generate client code directly from an OpenAPI spec — no third-party generator needed.</p><h4>Node.js</h4><p>Node.js relies heavily on community libraries like:</p><ul><li>axios for HTTP requests</li><li>grpc for gRPC</li><li>express-graphql for GraphQL</li></ul><p>While the ecosystem is vast, you often juggle different libraries and deal with version mismatches.</p><p><strong>Verdict:</strong></p><p>Ballerina is <strong>API-first and integration-ready</strong> out of the box.</p><p>Node.js excels in flexibility, but at the cost of consistency.</p><h3>5. Performance &amp; Scalability</h3><p>Both languages handle concurrency efficiently but in different ways.</p><h4>Node.js</h4><ul><li>Non-blocking I/O model (event-driven).</li><li>Perfect for I/O-heavy applications.</li><li>Horizontal scaling is easy with container orchestration (Kubernetes).</li></ul><h4>Ballerina</h4><ul><li>Has <strong>“strand-based concurrency”</strong>, a lightweight model inspired by coroutines.</li><li>Ideal for concurrent API calls and microservice chaining.</li><li>Supports distributed transactions and error handling natively.</li></ul><p><strong>Verdict:</strong></p><p>Node.js is time-tested for scale, but <strong>Ballerina’s concurrency model</strong> gives developers more control and predictability.</p><h3>6. Developer Experience Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*mwMWV4P7w60OZkfKMoS00g.jpeg" /></figure><h3>Conclusion</h3><p>Both Ballerina and Node.js are powerful in their own ways.</p><ul><li><strong>Choose Ballerina</strong> if you want a <strong>language built for modern cloud-native, API-first development</strong> with built-in observability and type safety.</li><li><strong>Choose Node.js</strong> if you value <strong>ecosystem maturity, package diversity, and JS familiarity</strong>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fd1e462695c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Ballerina is the Java for the Cloud-Native Era]]></title>
            <link>https://lasithmanaram.medium.com/why-ballerina-is-the-java-for-the-cloud-native-era-6eef6e0b5ba6?source=rss-be94a785d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eef6e0b5ba6</guid>
            <category><![CDATA[java-vs-ballerina]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[ballerina]]></category>
            <dc:creator><![CDATA[Lasith Jayalath]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 20:53:02 GMT</pubDate>
            <atom:updated>2025-10-24T20:53:02.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQdsIgFiKjWsf6YS67JbzQ.png" /></figure><h3>Introduction</h3><p>When Java first appeared in the 1990s, it revolutionized enterprise software by offering portability, object-oriented design, and a massive ecosystem. It quickly became <em>the</em> language for building scalable and reliable back-end systems.</p><p>But times have changed.</p><p>Today’s world revolves around <strong>microservices</strong>, <strong>APIs</strong>, <strong>cloud deployments</strong>, and even <strong>AI integrations</strong>. Developers now need languages that are cloud-aware by design, not retrofitted for it.</p><p>That’s where <strong>Ballerina</strong>, an open-source programming language created by <strong>WSO2</strong>, comes into the picture.</p><p>Ballerina has often been described as the <strong>“Java for the Cloud-Native Era”</strong> — and not without reason. It combines strong typing and enterprise-grade reliability (like Java) with built-in support for distributed systems, APIs, and observability (like a cloud platform).</p><p>In this article, we’ll explore why Ballerina earns that title — especially through its:</p><ul><li><strong>Built-in observability</strong></li><li><strong>OpenAPI-first development approach</strong></li><li><strong>Strongly typed data model system</strong></li></ul><h3>1. Observability as a First-Class Citizen</h3><p>In cloud-native systems, visibility is not optional — it’s essential.</p><p>You can’t fix what you can’t observe.</p><p>While Java developers often rely on <strong>external tools and libraries</strong> (like Micrometer, Prometheus, or Zipkin integrations) for metrics and tracing, Ballerina builds these right into the language runtime.</p><h4>Built-in Observability Features</h4><p>Ballerina offers:</p><ul><li><strong>Metrics</strong> (using Prometheus)</li><li><strong>Distributed tracing</strong> (via OpenTelemetry)</li><li><strong>Logs</strong> (structured and contextual)</li></ul><p>All this comes with <strong>zero external setup</strong>.</p><p>Here’s an example, observability in Ballerina can be turned on globally with just one configuration file:</p><pre>[ballerina.observe]<br>enabled = true<br>provider = &quot;default&quot;</pre><p>Once enabled, the runtime automatically tracks:</p><ul><li>Request latency</li><li>Service invocations</li><li>Error rates</li><li>Span traces between services</li></ul><p>You can view these metrics directly in your monitoring dashboards without extra instrumentation code.</p><p>This is a game changer compared to Java, where adding observability typically means wiring multiple libraries, exporters, and annotations.</p><blockquote>In short: Ballerina treats observability not as a plugin, but as a fundamental language feature.</blockquote><h3>2. Seamless OpenAPI Support</h3><p>One of Ballerina’s core strengths is its <strong>API-first philosophy</strong> — a key pillar of the modern microservices world.</p><p>While Java relies on frameworks like Spring Boot or Jakarta EE, where OpenAPI (Swagger) support is often an add-on, Ballerina makes it <strong>native</strong>.</p><h4>Code-to-Contract and Contract-to-Code</h4><p>Ballerina supports two-way interoperability with OpenAPI:</p><ol><li><strong>Generate Ballerina services from an OpenAPI definition</strong></li></ol><pre>bal openapi -i api_spec.yaml -o .</pre><p>This creates the entire service skeleton from your spec.</p><p><strong>2. Export OpenAPI definitions from existing Ballerina code</strong></p><pre>bal openapi export</pre><p>This generates an OpenAPI spec automatically — no annotations or extra libraries needed.</p><p>This two-way capability allows teams to:</p><ul><li>Collaborate effectively between backend, frontend, and documentation teams.</li><li>Maintain synchronization between API contracts and implementation.</li><li>Simplify API versioning and governance.</li></ul><blockquote>Ballerina’s OpenAPI integration makes it ideal for teams that live and breathe RESTful or AI-integrated microservices.</blockquote><h3>3. Typed Data Models — Strong, Safe, and Extensible</h3><p>One of Java’s defining features is <strong>type safety</strong> — catching errors at compile time instead of runtime.</p><p>Ballerina takes that idea and modernizes it for the <strong>data-driven API era</strong>.</p><p>Ballerina’s <strong>typed data models</strong> let you work confidently with structured data — whether it’s JSON from an API, XML from a message queue, or a record from a database.</p><h4>Example: JSON Binding in Ballerina</h4><pre>type User record {<br>    string name;<br>    int age;<br>    string email?;<br>};<br><br>service /users on new http:Listener(8080) {<br>    resource function post register(User user) returns string {<br>        return &quot;User registered: &quot; + user.name;<br>    }<br>}</pre><p>If a client sends a malformed request, the compiler and runtime validation will <strong>automatically reject</strong> it — ensuring data integrity and stability.</p><p>You don’t need extra frameworks like Jackson or Gson (as in Java).</p><p>The language natively understands the schema and enforces it.</p><blockquote>In short, Ballerina’s type system brings Java’s compile-time safety to the dynamic world of APIs.</blockquote><h3>4. Designed for Cloud and Microservices</h3><p>Ballerina is <strong>cloud-native by design</strong>.</p><p>It can:</p><ul><li>Deploy services as Docker containers automatically (bal build — cloud=docker)</li><li>Generate Kubernetes YAML files</li><li>Integrate easily with APIs, gRPC, WebSockets, GraphQL, and event streams</li></ul><p>These capabilities are not “add-ons.” They are part of the <strong>core build system</strong> — a step ahead of traditional Java microservice frameworks.</p><h4>Example: Deploying a Service to Docker</h4><pre>bal build --cloud=docker<br>docker run -d -p 8080:8080 my_ballerina_service</pre><p>This simplicity lets developers focus on <em>what</em> the service does, not <em>how</em> it’s deployed.</p><h3>Final Thoughts</h3><p>Ballerina doesn’t aim to replace Java — it evolves its philosophy.</p><p>It combines:</p><ul><li>Java’s <strong>type safety</strong> and <strong>enterprise strength</strong></li><li>Go’s <strong>simplicity</strong></li><li>Python’s <strong>developer friendliness</strong></li><li>And Kubernetes’ <strong>cloud-native spirit</strong></li></ul><p>In short, <strong>Ballerina is Java reborn for the API, AI, and cloud-native era</strong>.</p><p>It’s the language that understands modern software ecosystems — not as external systems to integrate with, but as <em>first-class elements</em> of programming.</p><p>So, if Java made sense for the enterprise in the 2000s,</p><p><strong>Ballerina makes sense for the cloud in 2025.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eef6e0b5ba6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ballerina vs Go: Building a Simple AI-Powered API with Hugging Face]]></title>
            <link>https://lasithmanaram.medium.com/ballerina-vs-go-building-a-simple-ai-powered-api-with-hugging-face-8af4b8a06718?source=rss-be94a785d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8af4b8a06718</guid>
            <category><![CDATA[ballerina]]></category>
            <category><![CDATA[ballerina-vs-golang]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Lasith Jayalath]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 14:57:08 GMT</pubDate>
            <atom:updated>2025-10-24T14:57:08.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czB42WKsLZUzC36Hm8_E4w.png" /></figure><h3>Introduction</h3><p>In today’s world of AI integrations, developers often need to quickly expose REST APIs that connect to external inference models — like those from <strong>Hugging Face</strong>.</p><p>While languages like <strong>Go (Golang)</strong> are already popular for backend development, <strong>Ballerina</strong> is an emerging, integration-friendly language designed specifically for networked and cloud-native applications.</p><p>In this article, we’ll:</p><ul><li>Build a simple <strong>AI text summarization API</strong> using <strong>Hugging Face’s BART model</strong></li><li>Implement it in <strong>both Ballerina and Go</strong></li><li>Compare their syntax, features, and developer experience side-by-side</li></ul><p>By the end, you’ll clearly understand when to pick each language and why.</p><h3>What We’re Building</h3><p>We’ll create a simple REST endpoint:</p><pre>POST /ai/generate</pre><p>It will accept plain text (like “Tell about Kumar Sangakkara”) and return a summary generated by <strong>Hugging Face’s</strong> model facebook/bart-large-cnn.</p><p>We’ll use the Hugging Face Inference API — which allows you to access pretrained models with an API key.</p><h3>Step 1: Create a Hugging Face API Key</h3><p>Please follow Part 2 of <a href="https://lasithmanaram.medium.com/building-your-first-ai-agent-in-ballerina-using-hugging-face-0343581aabbc">this article</a>.</p><h3>Step 2: Implementing with Ballerina</h3><pre>import ballerina/http;<br>import ballerina/log;<br><br>final string HF_API_KEY = &quot;Your_API_Token&quot;;<br>final string MODEL_URL = &quot;https://api-inference.huggingface.co/models/facebook/bart-large-cnn&quot;;<br><br>service /ai on new http:Listener(9090) {<br><br>    resource function post generate(http:Caller caller, http:Request req) returns error? {<br>        string|error prompt = req.getTextPayload();<br>        if prompt is error {<br>            check caller-&gt;respond(&quot;Invalid request payload&quot;);<br>            return;<br>        }<br><br>        string|error result = generateResponse(prompt);<br>        if result is error {<br>            log:printError(&quot;Error generating response&quot;, &#39;error = result);<br>            check caller-&gt;respond(&quot;Error generating response&quot;);<br>        } else {<br>            check caller-&gt;respond(result);<br>        }<br>    }<br>}<br><br>function generateResponse(string prompt) returns string|error {<br>    http:Client hfClient = check new (MODEL_URL, {<br>        auth: {<br>            token: HF_API_KEY<br>        }<br>    });<br><br>    json payload = { &quot;inputs&quot;: prompt };<br>    http:Response resp = check hfClient-&gt;post(&quot;&quot;, payload);<br><br>    json body = check resp.getJsonPayload();<br>    return body.toJsonString();<br>}</pre><p>Run it:</p><pre>bal run</pre><p>Test it:</p><pre>curl -X POST http://localhost:9090/ai/generate -d &quot;Tell about Kumar Sangakkara&quot;</pre><p>Response:</p><pre>[{<br>  &quot;summary_text&quot;: &quot;Kumar Sangakkara is a former Sri Lankan cricketer...&quot;<br>}]</pre><p>That’s it, a full working API in about 30 lines of Ballerina.</p><h3>Step 3: Implementing the Same in Go</h3><p>Here’s how the same logic looks in <strong>Go</strong>:</p><pre>package main<br><br>import (<br>    &quot;bytes&quot;<br>    &quot;encoding/json&quot;<br>    &quot;fmt&quot;<br>    &quot;io&quot;<br>    &quot;log&quot;<br>    &quot;net/http&quot;<br>)<br><br>const (<br>    HF_API_KEY = &quot;Your_API_Token&quot;<br>    MODEL_URL  = &quot;https://api-inference.huggingface.co/models/facebook/bart-large-cnn&quot;<br>)<br><br>type HFRequest struct {<br>    Inputs string `json:&quot;inputs&quot;`<br>}<br><br>func main() {<br>    http.HandleFunc(&quot;/ai/generate&quot;, handleGenerate)<br>    fmt.Println(&quot;Server running on http://localhost:9090/ai/generate&quot;)<br>    log.Fatal(http.ListenAndServe(&quot;:9090&quot;, nil))<br>}<br><br>func handleGenerate(w http.ResponseWriter, r *http.Request) {<br>    if r.Method != http.MethodPost {<br>        http.Error(w, &quot;Only POST allowed&quot;, http.StatusMethodNotAllowed)<br>        return<br>    }<br><br>    body, err := io.ReadAll(r.Body)<br>    if err != nil {<br>        http.Error(w, &quot;Failed to read request&quot;, http.StatusBadRequest)<br>        return<br>    }<br>    defer r.Body.Close()<br><br>    prompt := string(body)<br>    response, err := generateResponse(prompt)<br>    if err != nil {<br>        log.Printf(&quot;Error generating response: %v&quot;, err)<br>        http.Error(w, &quot;Error generating response&quot;, http.StatusInternalServerError)<br>        return<br>    }<br><br>    w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>    w.Write(response)<br>}<br><br>func generateResponse(prompt string) ([]byte, error) {<br>    payload := HFRequest{Inputs: prompt}<br>    jsonData, err := json.Marshal(payload)<br>    if err != nil {<br>        return nil, err<br>    }<br><br>    req, err := http.NewRequest(&quot;POST&quot;, MODEL_URL, bytes.NewBuffer(jsonData))<br>    if err != nil {<br>        return nil, err<br>    }<br><br>    req.Header.Add(&quot;Authorization&quot;, &quot;Bearer &quot;+HF_API_KEY)<br>    req.Header.Add(&quot;Content-Type&quot;, &quot;application/json&quot;)<br><br>    client := &amp;http.Client{}<br>    resp, err := client.Do(req)<br>    if err != nil {<br>        return nil, err<br>    }<br>    defer resp.Body.Close()<br><br>    if resp.StatusCode != http.StatusOK {<br>        body, _ := io.ReadAll(resp.Body)<br>        return nil, fmt.Errorf(&quot;HuggingFace API error: %s&quot;, body)<br>    }<br><br>    return io.ReadAll(resp.Body)<br>}</pre><p>Run:</p><pre>go run main.go</pre><p>Then test the service using the same curl command.</p><h3>Step 4: Ballerina vs Go — A Developer’s Perspective</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*daXzV6zplE_hxwKXT-DUZg.jpeg" /></figure><h3>In Summary</h3><ul><li><strong>Ballerina</strong> feels like it was <em>born for APIs</em>. JSON, HTTP, and Auth are first-class citizens.</li><li><strong>Go</strong> gives you full control — perfect for high-performance microservices or concurrent systems.</li></ul><p>Both are modern, lightweight, and production-ready — it just depends on your goal:</p><ul><li>Want to <strong>prototype and integrate quickly</strong> → Ballerina</li><li>Want <strong>maximum efficiency and low-level control</strong> → Go</li></ul><h3>Final Thoughts</h3><p>Both Go and Ballerina make building HTTP APIs easy, but they come from different design philosophies:</p><ul><li><strong>Ballerina</strong>: “Make network programming simpler.”</li><li><strong>Go</strong>: “Make systems programming simpler.”</li></ul><p>In this small Hugging Face integration, we saw how Ballerina’s <em>network-native design</em> helps developers focus on business logic instead of boilerplate.</p><p>If you’re looking to build APIs, integrations, or microservices that talk to AI models — Ballerina deserves your attention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8af4b8a06718" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>