Share My Creation Web API Template

Web API

Description: A boilerplate for creating CRUD based Web API.

web-api-help.png


Depends on following libraries: ByteConverter, JavaObject, jServer, Json, jSQL
1630138331344.png


Features:
  1. CRUD based - REST-API style (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.b4xtemplate" file into B4J platform Additional folder.
  2. Open B4J and create a new project with "Web API" template. Give your project any name you like, for e.g. WebAPI
  3. Run the project in Debug or Release mode. You will see something like this in the Logs:
    B4X:
    Web API server (version = 1.06) is running on port 19800
    Open the following URL from your web browser
    http://127.0.0.1:19800/v1/
  4. Copy the URL showed in Logs and open it using your web browser.

5. To connect to MySQL server, go to Objects folder and open "config.ini". Comment the SQLite section and uncomment the MySQL section.​
1630137963547.png
6. Edit the root password at line #42 (second last line). Save the file.​
7. In B4J project, comment the line '#AdditionalJar: sqlite-jdbc-3.36.0.2 and uncomment the line #AdditionalJar: mysql-connector-java-5.1.49-bin.​
Make sure you are using the correct version of connector.​
B4X:
#Region AdditionalJar
' MySQL connector
#AdditionalJar: mysql-connector-java-5.1.49-bin
' SQLite connector
'#AdditionalJar: sqlite-jdbc-3.36.0.2
#End Region
8. Follow step #3 above.​

Screenshot:
web-api.png


Client App (B4X):
B4A.png
. .
B4i.png
. .
B4J.png


Live demo: https://api.puterise.com:19900

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. 😄

Updates:
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
8/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)
6/9/2021
- WebAPI Client - v1.01
- - Some bugs fix and UI improvements
4/9/2021 - v1.09
- Fixed PutProductByCategoryAndId to update Product as different Category.
- WebAPI Client (B4X) - v1.00
2/9/2021 - v1.08
- Added ConfigureCORS for ajax request.
1/9/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/8/2021 - v1.06
- Support for SQLite database
 

Attachments

  • ajax-test.zip
    30.2 KB · Views: 60
  • Web API 1.09.zip
    454 KB · Views: 77
  • WebAPIClient 1.01.zip
    442.7 KB · Views: 77
  • Web API.b4xtemplate
    462.9 KB · Views: 33
  • WebAPIClient 1.02.zip
    443.3 KB · Views: 24
  • Web API 1.11.zip
    459.2 KB · Views: 0
Last edited:

swamisantosh

Member
Licensed 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
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
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.
 

aeric

Expert
Licensed 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.
 

aeric

Expert
Licensed 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
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
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.
 

aeric

Expert
Licensed User
v1.08
- Added ConfigureCORS for ajax request
 

aeric

Expert
Licensed 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
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
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

Member
Licensed 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: 15
  • error1.jpg
    error1.jpg
    449.8 KB · Views: 15
Last edited:

aeric

Expert
Licensed 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)
 

luke2012

Well-Known Member
Licensed 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