Share My Creation [Project Template] Web API Server


Version: 1.16
Description: Create Web API Server with CRUD functionalities

Sample application: [B4X] Todo List based on Web API

1681305482137.png
1681305567463.png
1681305621295.png


Template:
  • Web API Server (1.16).b4xtemplate
Depends on following libraries:
  • ByteConverter
  • JavaObject
  • jServer
  • Json
  • jSQL
Features:
  1. CRUD based - RESTful Web API (GET, POST, PUT, DELETE)
  2. Front-end (HTML, CSS, JS, Bootstrap)
  3. Support MySQL and SQLite database (Can be modified for MS SQL or SQL Express)
  4. Separate SQL queries file (queries-mysql.ini and queries-sqlite.ini)
  5. Sample database auto-generated for first run (Category and Product tables with dummy data)
  6. Versioning (using ROOT_PATH in config.ini, set as "/" if you don't want versioning)
  7. Auto generated documentation with API test.
How to use:
  1. Copy the "Web API Server (1.16).b4xtemplate" file into B4J Additional Libraries folder.
  2. Open B4J and create a new project with "Web API Server" template.
  3. Give your project any name you like, for e.g. WebAPI
  4. Run the project in Debug mode.
    You will see something like this in the Logs:
    B4X:
    Web API Server (version = 1.16) is running on port 19800
    Open the following URL from your web browser
    http://127.0.0.1:19800/v1/
  5. Copy the URL showed in Logs and open it using your web browser.
  6. To connect to MySQL server, go to Objects folder and open "config.ini".
  7. Comment the SQLite section and uncomment the MySQL section.
  8. Edit the root password at line #45 (second last line). Save the file.
    1681306109357.png
  9. In B4J project, comment the line
    '#AdditionalJar: sqlite-jdbc-3.39.3.0
    and uncomment the line
    #AdditionalJar: mysql-connector-java-8.0.30.
    Make sure you are using the correct version of connector.
    B4X:
    #Region AdditionalJar
    ' MySQL connector
    #AdditionalJar: mysql-connector-java-8.0.30
    ' SQLite connector
    '#AdditionalJar: sqlite-jdbc-3.39.3.0
    #End Region
  10. Follow step #3 above.
Client Template:
  • Web API Client (1.05).b4xtemplate
B4A
. .
B4i
. .
B4J


How to use:
  1. Copy the "Web API Client (1.05).b4xtemplate" file into B4X Additional Libraries folder.
  2. Open B4A (B4J or B4i) and create a new project with "Web API Client (1.05)" template.
  3. Edit the URL with your Web API Server host or IP
    B4X:
    Private URL As String = "http://192.168.50.42:17178/v1/" ' Change to your Web API Server URL
  4. Run in debug.
Video:

Comments: I try to make this template as compact as possible (remove user table and email function) but it is still big. If you don't like some features, just remove them. ?

12/04/2023
- Web API Server - v1.16
- Similar to Web API Template 2.0, it is now less confusing by using #Desc and #Path for documentation
- Web API Client - v1.0.5 (compatible with Web API Server v1.16)

03/10/2022
- Web API Server - v1.15
- JS: Fixed bug point to wrong id for Category dropdown in Edit dialog
- JS: Remove comma in thousand for price textbox in Edit dialog
- Add a Home button in Category page

01/10/2022
- Web API Server - v1.14
- Manage Category in new page
- Dynamic populate Category dropdown in add/edit product dialog
- Improve JS scripts
- SQLite version point to sqlite-jdbc-3.39.3.0

27/08/2022
- Web API Client - v1.0.4 (compatible with Web API Server v1.13)

25/08/2022
- Web API Server - v1.13
- Home page with Add, Edit and Delete Product (using Bootstrap modal and jQuery Validate)
- Help or API documentation page improvements
- Many variables and SQL commands are renamed!
- SQLite version point to sqlite-jdbc-3.39.2.0
- Separate Category and Product handlers
- FindHandler added for more search endpoints
- Endpoints structure changed!
- Warning: This version is not compatible with Web API Client v1.0.3 and below

28/05/2022
- Web API - v1.12 (fixed a bug in HelpHandler.bas when reading commented line)
- Updated to use jServer v4.0
- Web API Client - v1.0.3 (Converted to B4XTemplate)

26/01/2022
- Create Publish.zip using #CustomBuildAction
- Create Publish.zip using Comment Link

19/10/2021 - v1.11
- Better use of Connection Pool for MySQL (do not close pool)
- Change DataUtils module to DataConnector class
- Clean up some redundant codes

08/10/2021
- WebAPI Client - v1.02
- - Some bugs fix and UI improvements

24/9/2021 - v1.10
- Auto generated documentation/help file based on handler classes (Click on the Question mark icon on top right corner to access the help file)

06/09/2021
- WebAPI Client - v1.01
- - Some bugs fix and UI improvements

04/09/2021 - v1.09
- Fixed PutProductByCategoryAndId to update Product as different Category.
- WebAPI Client (B4X) - v1.00

02/09/2021 - v1.08
- Added ConfigureCORS for ajax request.

01/09/2021 - v1.07
- Changes in Utility module (ReturnSuccess and ReturnSuccess2) require Status Code.
- Changes in ProductHandler (PostCategory and PostProductByCategory) return new record as result with Status Code 201.

27/08/2021 - v1.06
- Support for SQLite database

About auto generated help file (version 1.10+)
https://www.b4x.com/android/forum/threads/web-api-template.133764/post-851114
 

Attachments

  • ajax-test.zip
    30.2 KB · Views: 1,192
  • Web API Server (1.16).b4xtemplate
    481.3 KB · Views: 615
  • Web API Client (1.05).b4xtemplate
    443.9 KB · Views: 633
Last edited:

swamisantosh

Member
Licensed User
Longtime User
I am not sure how deleting the sqlite file would solve the issue. The error was handled by try-catch and you can find the exact problem (LastException) by reading the logs while debugging. As I stated above, I have done a test to send POST request using the payload with invalid comma sign which caused the RequestData read invalid data. Maybe I should have validated the Map initialized from the RequestData. In you case, I am not sure how you produce the error. Since you already able to resolved the issue then it is good and I assume everything is good to go.

Until we found a new bug, I hope the current version is a good template to start your own project. I encourage anyone to modify this template and come out an improved version. For myself, I would add back the user token, API key and SMTP features for my own use. I am not sharing it because a template should be minimalist and serve as a starting point for own customization.

Thanks everyone for the likes and testing this template. ??

Don’t worry, I will keep answering your questions if you have one about this template. ?
We would be thankful , if you can keep share future development Web API Template . just for purpose of learning only
 

peacemaker

Expert
Licensed User
Longtime User
Mobile operators are often blocking many ports. And only 80 or 443 (HTTPS) are for sure available.
So, is it OK for such applications ?
 

aeric

Expert
Licensed User
Longtime User
Mobile operators are often blocking many ports. And only 80 or 443 (HTTPS) are for sure available.
So, is it OK for such applications ?
I don't have problem with my (VPS) hosting. My apps are able to connect to it.
If any hosting provider block your ports then you may need to contact them to open the ports for you.
Not sure about Mobile operators. My mobile ISP doesn't block.
 

peacemaker

Expert
Licensed User
Longtime User

Not hosting. Mobile operators of users who try to use the server from their mobile phones (clients), but the port like 59000 is locked. And cannot be unlocked for sure.
 

aeric

Expert
Licensed User
Longtime User
Not hosting. Mobile operators of users who try to use the server from their mobile phones (clients), but the port like 59000 is locked. And cannot be unlocked for sure.
Not sure about the ISP in your country. As long as the port number doesn't exceed 65,535 I think it should be fine. If we use smaller port number, it is likely would conflict with some reserved ports. If I am hosting multiple apps on the same server, then it is not ideal to only host the apps on the same ports (80 and 443). If this is the case then I think you have no choice but to use different domain or create subdomain. I am not expert on this topic and this is what I understand.
 

peacemaker

Expert
Licensed User
Longtime User
to use different domain or create subdomain

Ah, clear, so, for 80 port we have to host the app on separate subdomain to solve the trouble with mobile operator ports.
Clear, thanks.
 

aeric

Expert
Licensed User
Longtime User
Ah, clear, so, for 80 port we have to host the app on separate subdomain to solve the trouble with mobile operator ports.
Clear, thanks.
I think so. If you are hosting B4J server apps, I guess you have full control on the port numbers of the firewall. In my case, my VPS is running on Ubuntu Linux and I can open all ports. This is similar on Windows server where you can control which ports to allowed or which IP addresses to whitelist. Unless this settings are blocked by the hosting provider by default. On the Mobile operator side, you may need to find out. If ports 80 and 443 are the only allowed port numbers, then I guess using different subdomain may solve the issue for hosting multiple apps.
 

Roberto P.

Well-Known Member
Licensed User
Longtime User
HI Aeric,
thank for your work.

awesome template and starting point for API development with B4J.

I believe this needs to be natively enhanced and integrated into B4J. We have now entered the era of APIs and the Native Cloud.

Why use Node.js or Spring Boot when we have B4J available which is simpler, lighter and has a lot of libraries?

Regards
 

aeric

Expert
Licensed User
Longtime User
I didn't understand
I suppose I have provided sufficient information about this project (or am I posting too much that anyone would not interested to read further) in the first post.
The history or background of how this project was born is from the following post:
[Wish] B4J as a Powerful Web API Development Tool

Actually, I never thought to create it myself.
btw, where can i download your API template above?
I have no idea. I am not sure I will create it.

But then I created it.
Note that anyone can create new project templates.

I consider this project as a "proof of concept". However, if I continue to update it, one day it might become a tool for building app aiming for production. I have seen something like Django and Yii framework to quickly scaffold a project.

Now, my question is:
Do you think I should create a client app (using B4A, B4i or B4J and even html+ajax or other languages such as PHP, ASP.NET, VB.NET) to consume the API of this template? (to further explain what this template could be use for)
 

aeric

Expert
Licensed User
Longtime User
A simple example of consuming the API would be AWESOME! GREAT JOB ON THIS TEMPLATE!!
I just uploaded a sample html page (ajax-test.zip) in the first post. By the way, if you have created a project with this template, the search function at the bottom also demonstrate how to consume the API using AJAX. I will create some B4X client apps if I am free later.
 

aeric

Expert
Licensed User
Longtime User
I just uploaded a sample html page (ajax-test.zip) in the first post.
I created this html test for checking the CORS filter I added in version 1.08.

To test CORS is working or not, restrict the B4J Web API app with the following (line #108):
B4X:
ConfigureCORS(ROOT_PATH & "category/*", "http://127.0.0.1:19800", "", "") ' test.html

Then edit the url in html file:
HTML:
<!DOCTYPE html>
<html>
<head>
    <title>CORS TEST</title>
    <script type="text/javascript" src="jquery.min.js">
    </script>
</head>
<body>
    <div>
        <p class="id">ID: </p>
        <p class="name">Name: </p>
        <div id="data"></div>
    </div>
</body>
</html>
<script type="text/javascript">
    $(document).ready(function()
    {
        $.ajax(
        {
            url: "http://127.0.0.1:19800/v1/category/2/product/"
        }).then(function(data, status, jqxhr)
        {
            $('.id').append(data.r[0].id);
            $('.name').append(data.r[0].product_name);
            $.each(data.r, function()
            {
                $('#data').append('<p>');
                $.each(this, function(key, value)
                {
                    $('#data').append(key +': '+ value+'<br>');
                });
                $('#data').append('</p>');
            });
            console.log(jqxhr);
        });
    });
</script>

Try open the HTML locally (just double-click), put it inside Laragon (or XAMP server) running on different port number or upload to your hosting.
Right-click the browser and Inspect (Ctrl+Shift+I). Click Console tab, you will see:
Access to XMLHttpRequest at 'http://127.0.0.1:19800/v1/category/2/product/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Failed to load resource: net::ERR_FAILED

p/s: I am not expert on this topic. I guess I am doing it correctly.
 

yaqoob

Active Member
Licensed User
Longtime User
Hi aeric,

Thank you for share your creation. I am getting the error ("Utility - 31: Unknown type: json<br />Are you missing a library reference?" see file error1. Even though the library Json is selected and B4J is the latest version (9.10) see file error2. I noticed you are using JSON 1.2, but what is available as the internal library is 1.10. I did what you suggested in post 4 to update the JSON library, but still, I am getting the same error.

Any suggestions?
 

Attachments

  • error2.png
    error2.png
    243.2 KB · Views: 286
  • error1.jpg
    error1.jpg
    449.8 KB · Views: 289
Last edited:

aeric

Expert
Licensed User
Longtime User
Hi aeric,

Thank you for share your creation. I am getting the error ("Utility - 31: Unknown type: json<br />Are you missing a library reference?" see file error1. Even though the library Json is selected and B4J is the latest version (9.10) see file error2. I noticed you are using JSON 1.2, but what is available as the internal library is 1.10.

Any suggestions?
You need the latest version of JSON library (version 1.20)
 

yaqoob

Active Member
Licensed User
Longtime User
Thank you for your feedback. It is working now. The mistake I have done copied the JSON library file to the additional library. Once I moved them to B4J internal library it worked
 

luke2012

Well-Known Member
Licensed User
Longtime User
WOW. Outstanding work :)
This is a REST API Server implementation ?
This web api could be called by Angular apps using REST API Client ?
 
Top