B4J Tutorial [web]Tutorial - Using Web API Controller

Introduction

This tutorial is based on Web API Template 2 (version 2.03) on how to use Web API Controller library.
At the time of writing, the library is version 1.01.
For this tutorial, we will cover on using this library for creating API controller. For Web controller, you can refer to IndexController.

How to install

Download WebAPIController.zip from here and unzip the file into B4J Additional folder.
1686322108573.png


Add a new Controller

You can open your existing or start a new Web API Template 2 project.
Right-click on the Controllers group under Modules tab, Add New Module -> Class Module and select Web API Controller.
1686322977397.png


Enter a name for your Controller, eg. ProductController
1686323282113.png


This will add a boilerplate controller class with "Item" as the default model.
You can use Search on this module to find the word "Item" and replace with the word "Product".
Click on "Current Module" button to make changes. DO NOT replace with "All Modules" button.
1686324547248.png

At this stage, you will get some errors in the code because some variables are not yet added.
Now navigate to ApiHandler class, under Sub ProcessRequest, add the following highlighted code:
B4X:
Select ControllerElement
    Case "data"
        Dim Data As DataController
        Data.Initialize(Request, Response)
        Data.Route
        Return
    Case "product"
        Dim Product As ProductController
        Product.Initialize(Request, Response)
        Product.Route
        Return
End Select

1686325394289.png


We still get some errors because the controller is using MinimaList by default.
We need to declare this variable in Main module so we can use it in our controller.
1686326154517.png

To load the persisted data from KeyValueStore, add the following code in Sub ConfigureKeyValueStore.
To write to KVS, check Sub WriteKVS.
B4X:
If MinimaProduct.IsInitialized Then
    MinimaProduct.List = KVS.GetDefault("ProductList", MinimaProduct.List)
End If
1686326457398.png


It is done. Now, no more errors reported.

Final step, to allow us to test the new API in Help, we need to add our new controller in Sub ConfigureControllers of Main module.
1686328018832.png


Try run your project and navigate to API Documentation / Help to test the API.

Testing the API

Let's make a POST call. You can copy the sample JSON body in the light blue box on the left and paste to the white box in the center.
Click on Submit button and you should see the response.
1686326875972.png


Stop the debug.

Run the Debug and navigate to Help page again.

Now try to make a GET call. Simply click on the green Submit button.

If the Response box returns an object, meaning the data is successfully persisted in KeyValueStore.

The data file is name kvs.dat inside Objects folder.
1686327028115.png


Thanks for following this tutorial.

Regards,
Aeric
 
Last edited:

aeric

Expert
Licensed User
Longtime User
How to use #Plural?

For usual practice, use either only singular or plural is recommended, not both.
Even though it is not a good practice, this API template allows to create a controller with a singular item and a plural with GET method.

E.g.
GET /web/api/v2/items <-- plural, return all items
GET /web/api/v2/item/1 <-- singular, return item corresponding to the id

In Sub ProcessRequest of ApiHandler class, add the plural word together with the singular word. This will call the same controller class.
B4X:
Select ControllerElement
    Case "item", "items"
        Dim Item As ItemController
        Item.Initialize(Request, Response)
        Item.Route
        Return
End Select

In Sub RouteGet of ItemController, write as following:
B4X:
' Router for GET request
Private Sub RouteGet
    Select Version
        Case "v2"
            Select ElementLastIndex
                Case ControllerIndex
                    Dim ControllerElement As String = Elements(ControllerIndex)
                    Select ControllerElement
                        Case "items"
                            GetItem
                            Return
                    End Select
                Case FirstIndex
                    Dim FirstElement As String = Elements(FirstIndex)
                    If Utility.CheckInteger(FirstElement) = False Then
                        Utility.ReturnErrorUnprocessableEntity(Response)
                        Return
                    End If
                    GetOneItem(FirstElement)
                    Return
            End Select
    End Select
    Utility.ReturnBadRequest(Response)
End Sub

Remember to add #Plural as comment
B4X:
Private Sub GetItem
    ' #Plural = items
    ' #Version = v2
    ' #Desc = Read all Items in MimimaList
    HRM.ResponseData = Main.MinimaItem.List
    HRM.ResponseCode = 200
    If Main.SimpleResponse Then
        Utility.ReturnSimpleHttpResponse(HRM, "List", Response)
    Else
        Utility.ReturnHttpResponse(HRM, Response)
    End If
End Sub

Edit:
If your controller is in plural form and you want to use singular route, you can use the #Plural comment to overwrite it.
 
Last edited:
Top