Search code examples
clientballerina

What is the best practice to use the clients in ballerina


import ballerina/http;
import booksvc.googlebooks as gb;

service / on new http:Listener(9090) {
    resource function get books() returns gb:Book[]|http:InternalServerError {
        gb:Book[]|error books = gb:loadBooks();
        if books is error {
            return http:INTERNAL_SERVER_ERROR;
        } 
        return books;
    }

    resource function get author(string bookname) returns string|http:InternalServerError {
        string|error name = gb:getAuthor(bookname);
        if name is error {
            return http:INTERNAL_SERVER_ERROR;
        }
        return name;
    }
}

I have to use the OpenApi client for functions loadbooks and getAuthor. What is the best practice to initialize the client and use it in those functions?


Solution

  • import ballerina/http;
    import booksvc.googlebooks as gb;
    
    service / on new http:Listener(9090) {
        private final http:Client googleBooks;
    
        function init() returns error?{
            self.googleBooks = check new("https://www.googleapis.com/books/v1/volumes", {auth: {token: apiKey}});
        }
    
        resource function get books() returns gb:Book[]|http:InternalServerError {
            gb:Book[]|error books = gb:loadBooks(self.googleBooks);
            if books is error {
                return http:INTERNAL_SERVER_ERROR;
            } 
            return books;
        }
    
        resource function get author(string bookname) returns string|http:InternalServerError {
            string|error name = gb:getAuthor(bookname, self.googleBooks);
            if name is error {
                return http:INTERNAL_SERVER_ERROR;
            }
            return name;
        }
    }
    

    Maintain the client as private final variable at the service level and initialize it inside the service init function. Then pass that as parameter to loadBooks and getAuthor functions.