Make Your Integration Seamless By Using Ballerina Client Connectors
Learn how to use the Ballerina OpenAPI tool to generate the ballerina client connector.
Join the DZone community and get the full member experience.
Join For FreeConnectors and SDKs
This is the era where we can see the face of the rapid growth in the integration space. There several dynamic entities have been added to the space, such as cloud networking, mobile network, IoT, system API, and so on. To use those dynamics, there should be any medium to communicate with each other.
Connectors and SDKs are the medium for connecting integration entities to each other.
With respect to the other programming languages, we can have a Software Development tool Kit (SDK) for communicating with those services. There are two types of SDKs. One is Client SDK and Server SDK. Commonly we use a client SDK for accessing the services from service providers.
Benefits of Having Connectors and SDKs
- A client SDK contains wrapper classes that you can use to call the API from your application without having to deal with HTTP requests and responses. What SDK does is reduce the complexity of accessing direct API calls in third-party integration. Those complexities can be authorization, authentication, call API for accessing another API, data normalization, etc.
- SDK makes your integration seamless and fast.
- Creating a friendly view for accessing a REST API.
- Built-in support and expertise: No need to worry about the API-consuming knowledge. When using the SDK, you don’t need to worry about the direct API complexity that we discussed above. Only you need to provide the input for your request, and it will return the expected output as a response. As example it is just a function call `yourSDK.getAPIDetails()`
If you have any open API specifications, SwaggerHub lets you generate client SDKs for JavaScript, Java, C#, Objective C, Swift, Android, and many other languages.
In terms of connectors, we can simply introduce connector as an SDK with respect to commonly defined as a set of tools that can be used to create and develop applications.
Ballerina Client Connectors
When it comes to the Ballerina Client Connector, it is almost similar to the client SDK, which is in other languages discussed above. Ballerina connectors let the developers using your API follow some common patterns that are more familiar to them. It is capable of consuming the API and accessing ballerina connector actions. Those actions are mapped to the ballerina remote function defined in your open API spec with operations.
Let’s discuss how ballerina helps you to own your client connector for the open API specification. There are two options available for generating connectors in ballerina.
- Option 01: Manually written ballerina code for ballerina client according to the API specification.
- Option 02: Use the Ballerina OpenAPI tool for generating the ballerina client only by providing your OpenAPI specification.
You can go with Option 01 if you know the API design, but you haven't an API specification for the system. You can go with option 02 if you have an open API specification.
Furthermore, we are explaining the second option of how you can use the Ballerina OpenAPI tool to make your coding life easy.
Ballerina OpenAPI Tool
The Ballerina OpenAPI tool will make it easy for you to start the development of a service documented in an OpenAPI contract in Ballerina by generating a Ballerina service and client skeletons. It enables you to take the code-first API design approach by generating an OpenAPI contract for the given service implementation.
If you are new to ballerina OpenAPI tool, Don't worry Here is the good stage to getting to know it.
As we stated before, here is the step to follow to create a client connector.
Step 01:
Create a ballerina package by running the `bal new <package name>` and going inside it.
Step 02:
For the client connector, you need to generate a client stub with respect to the given open API specification. It can be used in your applications to call the service defined in the OpenAPI file.
Run the below command to generate a client. Simply, you require only to provide your valid OpenAPI specification as an input to the below Ballerina command. If you are not familiar with the YAML format in swagger, then we are available for your specification with JSON format as well.
bal openapi -i openapi.yaml/openapi.json –mode client
You can take the advantage of grouping your operation in the specification using tags. The Ballerina OpenAPI tool also provides the capability for generating your connectors for given tags.
For example: let’s assume your large OpenAPI specification has grouped with tag1, tag2, etc. If you use the below command you can generate a connector for a given tag1.
bal openapi -i <openapi.yaml/openapi.json> --mode client --tags “tag1”
This will generate a Ballerina client stub (client.bal), a util file (utils.bal) for the relevant utils methods related to the client stub, and a schema file (types.bal) for the hello.yaml OpenAPI contract.
- client.bal: This ballerina file contains all the implementation for operation API in open API spec.
- type.bal: This contains all the open API schema related details.
- utils.bal: This contains util functions that are required to process remote action in api call.
Almost we have created client stub and you can use this generated client in you ballerina application to consume APIs.
Code Demonstrates
To understand well, I will exemplify how you can use client connectors in your application.
Here I take mock API specifications for pet stores. It has one get operation with endpoint `/pet` returning a list of Pet objects.
openapi: 3.0.0
info:
title: Sample API
version: 0.1.0
servers:
- url: http://localhost:9090/v1
paths:
/pet:
get:
summary: Returns a list of pets.
operationId: getPetList
responses:
'200': # status code
description: A JSON array of pets
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/Pet"
'500':
description: "Internal Server Error"
components:
schemas:
Pet:
type: object
properties:
name:
type: string
age:
type: integer
Generated client.bal by executing this command bal openapi -i pet store.yaml --mode client
import ballerina/http;
public isolated client class Client {
final http:Client clientEp;
# Gets invoked to initialize the `connector`.
#
# + clientConfig - The configurations to be used when initializing the `connector`
# + serviceUrl - URL of the target service
# + return - An error if connector initialization failed
public isolated function init(http:ClientConfiguration clientConfig = {}, string serviceUrl = "http://localhost:9090/v1") returns error? {
http:Client httpEp = check new (serviceUrl, clientConfig);
self.clientEp = httpEp;
return;
}
# Returns a list of pets.
#
# + return - A JSON array of pets
remote isolated function getPetList() returns Pet[]|error {
string resourcePath = string `/pet`;
Pet[] response = check self.clientEp->get(resourcePath);
return response;
}
}
Here the client is initialized with the details according to openAPI contract server section. Operation GET details to represent under the remote function name with getPetList.
Let's time to check how we invoke this generated client function in your system.
Create another ballerina file and update the file by creating a client instant and consume an API using remote functions in the client.bal file.
import ballerina/io;
public function main() returns error? {
io:println("Get pets details");
// Create client instanct for use in the application
Client petClient = check new ();
// Create a function call for concume the API
Pet[] petList = check petClient->getPetList();
// DO the data process
}
Bonus tip for developers who need to reuse their client connector for several projects
You can globally host your package by publishing it to ballerina central. For that, you need to do a few additional steps mentioned below.
Step 3:
Now we are already completed halfway to generating a client connector. Now let's proceed with the few actions to see your connector in ballerina central.
Let’s have a quick look at how you can publish it in the Ballerina central.
Create a Package.md file by adding the details of your connector.
Then run the
bal build
command to make sure your connector is free with any error. It would be great if you can run a few test cases to check the API functionality. If you run `bal openapi -i openapi.yaml –mode client –with-test` extra `test.bal` file will be generated, including tests to your remote function.When the build is successful, Execute the
bal pack
command to generate the Ballerina archive.Follow the step here for publish to package in central repository.
After publishing the package, you can import the package for your future application. ex: import ballerina/<your package>
Conclusion
As we state before, connectors are a bunch of functions or templates that can be used to get the necessary data by calling relevant API. It is a user-friendly approach for accessing data through REST API. Simply we can say the connectors are the medium for serving API data for you.
Typically Main companies have their API system with 400, 600 operations. It will be painful if a developer is going to code it manually. Therefore we make it easy to create your client connector using the Ballerina OpenAPI Tool with the proper OpenAPI specification. Happy reading!
Opinions expressed by DZone contributors are their own.
Comments