B4A Library ✨ Magic API Library: Build a Powerful Server-Side REST API with MySQL and File Management in Just 5 Minutes! 🚀

⚡️ Unleash the API Power: Magic API for Seamless B4X Integration

? Greetings, B4X enthusiasts! Today, I'm thrilled to unveil the magic behind our latest creation—the Magic API. Elevate your B4X applications with streamlined API integration, simplifying CRUD operations effortlessly. From uploading api.php to securing your connection data, this library is your key to seamless integration. Explore its advantages and fortify your data integrity with advanced security measures. Let's dive into the API revolution!

? Advantages of Magic API:
Unlock the Magic: Seamlessly integrate API functionality into your B4X applications.
Effortless CRUD Operations: Create, Read, Update, and Delete with ease, optimizing data management.
? Advanced Security Measures: API key authentication, HTTPS encryption, and input validation ensure data confidentiality and integrity.
? Base URL: http://example.com/api.php
? User-Friendly Initialization: Just upload, edit the header with your connection data, and you're ready to communicate!


?Usage Instructions:

1. Upload the api.php file to your server.
2. Edit the header with your connection data.
3. You're ready to communicate your app with your mobile and desktop applications.

Note: The API works fine without the library, but the library will help you communicate more easily.

? Explore API Documentation:

API Documentation​

Security​

The API employs several security measures to ensure the integrity and confidentiality of your data:

  • Authentication: All API requests require an API key to be included as a query parameter. This key uniquely identifies the client making the request and provides access control to the API endpoints.
  • HTTPS: Communication with the API is always encrypted over HTTPS, ensuring that data transmitted between the client and the server remains confidential.
  • Input validation: The API performs input validation and sanitization to prevent common security vulnerabilities such as SQL injection or cross-site scripting (XSS) attacks.

Base URL​

Authentication​

The API uses an API key for authentication. The API key must be included as a parameter in all requests.

Authentication Parameters​

  • api_key (required): The API key to authenticate the request.

Available Resources​

GET /api.php​

Retrieve records from a table.

Parameters​

  • table (required): The name of the table from which you want to retrieve records.
  • id (optional): The ID of the specific record you want to retrieve.
  • column and value (optional): The name of a column and its value to filter the records.
  • comparison (optional): The comparison operator to use in the search. It can be >, <, >=, or <=.

Examples​


Retrieve all records from a table:



GET api.php?table=example&api_key=your_api_key



Retrieve a specific record by ID:



GET api.php?table=example&id=1&api_key=your_api_key



Retrieve records filtered by a column and its value:



GET api.php?table=example&column=age&value=25&api_key=your_api_key



Retrieve records with comparison:



GET api.php?table=example&column=age&value=25&comparison=>&api_key=your_api_key



POST /api.php​

Create a new record in a table.

Parameters​

  • table (required): The name of the table in which you want to create the record.

Request Body​

You must provide the data for the new record in JSON format in the request body.

Example​

POST /api.php?table=example&api_key=your_api_key


{
"name": "John Doe",
"age": 30,
"email": "johndoe@example.com"
}

PUT /api.php​

Update an existing record in a table.

Parameters​

  • table (required): The name of the table in which the record exists.
  • id (required): The ID of the specific record you want to update.

Request Body​

You must provide the updated data for the record in JSON format in the request body.

Example​


Update a record by ID in the "example" table:



PUT api.php?table=example&id=1&api_key=your_api_key


Request Body:



{
"age": 30
}



Update records by column and value in the "example" table:



PUT api.php?table=example&column=name&value=John&api_key=your_api_key


Request Body:



{
"age": 30
}



Update records by comparison:



PUT /api.php?table=example&column=age&value=25&comparison=>&api_key=your_api_key


{
"age": 35
}



DELETE /api.php​

Delete records from a table.

Parameters​

  • table (required): The name of the table from which you want to delete records.
  • id or column and value (required): You can provide the ID of the specific record you want to delete, or use a column and its value to filter the records.
  • comparison (optional): The comparison operator to use in the search. It can be >, <, >=, or <=.

Examples​


Delete a record by ID in the "example" table:


DELETE /api.php?table=example&id=1&api_key=your_api_key

Delete records by column and value in the "example" table:


DELETE /api.php?table=example&column=age&value=25&api_key=your_api_key

Delete records by comparison:


DELETE /api.php?table=example&column=age&value=25&comparison=>&api_key=your_api_key

Remember to replace your_api_key with your actual API key.




MagicApi library
# B4X Library Documentation

## Description
This library provides methods for performing CRUD (Create, Read, Update, Delete) operations on an API. It is designed to interact with an API that uses JSON as the data exchange format.

## Installation
1. Download the MagicApi.b4xlib library file.
2. Copy the MagicApi.b4xlib file to the additional libraries folder in your B4X development environment.

## Initialization
Before using the library methods, you need to initialize it by calling the `Initialize` method and providing the following parameters:
- `CallbackModule` (Object): the name of the callback module where the events handling API responses are located.
- `cEventname` (String): the base name for the response events.
- `urlbase` (String): the base URL of the API.
- `api_key` (String): The api key defined in the php file.

## Events
The library generates response events for each CRUD operation. These events should be implemented in the specified callback module during initialization.

### Generated Events
- `EventName_Insertmaps(m As Map, success As Boolean)`
- `EventName_Delete(tablename As String, success As Boolean)`
- `EventName_DeleteByColumn(tablename As String, success As Boolean)`
- `EventName_Update(tablename As String, success As Boolean)`
- `EventName_UpdateByColumn(tablename As String, success As Boolean)`
- `EventName_SearchforId(m As Map, success As Boolean)`
- `EventName_GetTable(x As List, success As Boolean)`
- `EventName_Search(x As List, success As Boolean)`

## Methods

Insertmaps(maps As Map, tablename As String)


Performs an insertion operation on the specified table of the API.
Example usage:
Dim data As Map
data.Initialize
data.Put("Column1", "Value1")
data.Put("Column2", "Value2")
MagicApi.Insertmaps(data, "table")

Delete(tablename As String, id As String)​

Deletes a record from the specified table of the API using the ID.
Example usage:
MagicApi.Delete("table", "12")

DeleteByColumn(tablename As String, column As String, value As String)​

Deletes records from the specified table of the API using a column and a value.
Example usage:
MagicApi.DeleteByColumn("table", "column", "value")

DeleteByColumn_comparison(tablename As String, column As String, value As String,comparison As String)​

Deletes records from the specified table of the API using a column and a value and comparison <,>,<=,>=.
Example usage:
MagicApi.DeleteByColumn_comparison("table", "age", "20",">")

Update(tablename As String, id As String, data As Map)​

Updates a record in the specified table of the API using the ID and the provided data.
Example usage:
Dim data As Map
data.Initialize
data.Put("Column1", "NewValue1")
data.Put("Column2", "NewValue2")
MagicApi.Update("table", "12", data)

UpdateByColumn(tablename As String, column As String, value As String, data As Map)​

Updates records in the specified table of the API using a column, a value, and the provided data.
Example usage:
Dim data As Map
data.Initialize
data.Put("Column1", "NewValue1")
data.Put("Column2", "NewValue2")
MagicApi.UpdateByColumn("table", "column", "value", data)

UpdateByColumn_comparison(tablename As String, column As String, value As String,comparison As String, data As Map)​

Updates records in the specified table of the API using a column, a value, and the provided data and comparison <,>,>=,<=.
Example usage:
Dim data As Map
data.Initialize
data.Put("Column1", "NewValue1")
data.Put("Column2", "NewValue2")
MagicApi.UpdateByColumn_comparison("table", "age", "15",">=", data)

SearchforId(tablename As String, id As String)​

Searches for a record in the specified table of the API using the ID.
Example usage:
'
MagicApi.SearchforId("table", "123")
wait for eventname_SearchforId(m As Map, success As Boolean)
if success = true then
m.get("Column 1")
m.get("Column 2")
else

end if

GetTable(tablename As String)​

Gets all records from the specified table of the API.
' Example usage:
MagicApi.GetTable("table")
Wait For eventname_GetTable(x As List, success As Boolean)
    For Each col As Map In x
        col.Get("Column name1")
        col.Get("Column name 2")
    Next

Search(tablename As String, column As String, value As String)​

Performs a search in the specified table of the API using a column and a value.
' Example usage:
MagicApi.Search("table", "column", "value")
wait for EventName_Search(x as list, success as Boolean)
if success = true then
 For Each col As Map In x
col.Get("Column name1")
col.Get("Column name 2")
next
else

end if

sub


Search_comparison(tablename As String, column As String, value As String,comparison As String)​

Performs a search in the specified table of the API using a column and a value and comparison.
' Example usage:
MagicApi.Search_comparison("table", "age", "35","<=")
wait for EventName_Search(x as list, success as Boolean)
if success = true then
 For Each col As Map In x
col.Get("Column name1")
col.Get("Column name 2")
next
else

end if

sub


Complete Example​


example:
Sub Process_Globals
    Private magicApi As MagicApi
End Sub

Sub Globals
    ' ...
End Sub

Sub Activity_Create(FirstTime As Boolean)
    ' ...
    magicApi.Initialize(Me, "MyEventName", "http://example.com")
End Sub

' Implement the events generated by the library
Sub MyEventName_Insertmaps(m As Map, success As Boolean)
    ' ...
End Sub

Sub MyEventName_Delete(tablename As String, success As Boolean)
    ' ...
End Sub

' Implement other generated events...

Sub SomeSub
    ' Examples of using the library methods
    Dim data As Map
    data.Initialize
    data.Put("Column1", "Value1")
    data.Put("Column2", "Value2")
    magicApi.Insertmaps(data, "table")

    magicApi.Delete("table", "123")

    magicApi.DeleteByColumn("table", "column", "value")

    Dim updateData As Map
    updateData.Initialize
    updateData.Put("Column1", "NewValue1")
    updateData.Put("Column2", "NewValue2")
    magicApi.Update("table", "123", updateData)

    magicApi.UpdateByColumn("table", "column", "value", updateData)

    magicApi.SearchforId("table", "123")

    magicApi.GetTable("table")

    magicApi.Search("table", "column", "value")
End Sub


MagicAPI Module - New Routines

1. InsertOrUpdateMapForColumnValue

Description:
This routine checks whether a record exists in the specified table by searching for a column value. If the record exists, it updates the record; if not, it inserts a new record.

Parameters:

  • tablename (String): The name of the table where the operation will take place.
  • searchColumn (String): The column used for the search.
  • searchValue (String): The value to look for in the searchColumn.
  • data (Map): The data to insert or update.
Event Triggered:
<EventName>_InsertOrUpdateMapForColumnValue(message As String, success As Boolean)

  • message can be "Insert", "Update", or "Error".
  • success indicates if the operation was successful.

Example 1: Insert or Update a User Record

' Example usage - Insert or Update:
Dim userData As Map
userData.Initialize
userData.Put("name", "John Doe")
userData.Put("email", "john.doe@example.com")
userData.Put("age", 30)

MagicAPI.InsertOrUpdateMapForColumnValue("users", "email", "john.doe@example.com", userData)

Wait For MagicAPI_InsertOrUpdateMapForColumnValue(message As String, success As Boolean)

If success Then
Select Case message
Case "Insert" Log("A new user record was inserted.")
Case "Update" Log("The existing user record was updated.")
End Select
Else Log("Error: Unable to perform the operation.")
End If


Example 2: Insert or Update a Product Record

' Example usage - Insert or Update Product:
Dim productData As Map
productData.Initialize
productData.Put("name", "Wireless Mouse")
productData.Put("price", 29.99)
productData.Put("stock", 100)

MagicAPI.InsertOrUpdateMapForColumnValue("products", "name", "Wireless Mouse", productData)

Wait For MagicAPI_InsertOrUpdateMapForColumnValue(message As String, success As Boolean)

If success Then
Select Case message
Case "Insert"
Log("A new product record was inserted.")
Case "Update"
Log("The existing product record was updated.")
End Select
Else Log("Error: Unable to perform the operation.")
End If


2. InsertMultipleMaps

Description:
This routine inserts multiple records into the specified table using a list of maps, where each map represents a record.

Parameters:

  • ListOfMaps (List): A list of maps containing the data to insert. Each map represents one record.
  • TableName (String): The name of the table where the records will be inserted.
Event Triggered:
<EventName>_Insertmaps(m As Map, success As Boolean)

  • m: The map representing the data that was inserted.
  • success: Indicates if the operation was successful.

Example 1: Insert Multiple User Records

' Example usage - Insert Multiple Users:
Dim userRecords As List
userRecords.Initialize

Dim user1 As Map
user1.Initialize
user1.Put("name", "Alice")
user1.Put("email", "alice@example.com")
user1.Put("age", 25)

Dim user2 As Map
user2.Initialize
user2.Put("name", "Bob")
user2.Put("email", "bob@example.com")
user2.Put("age", 28)

userRecords.AddAll(Array(user1, user2))

MagicAPI.InsertMultipleMaps(userRecords, "users")

Wait For MagicAPI_Insertmaps(m As Map, success As Boolean)

If success Then
Log($"Record inserted: ${m}"$)
Else Log("Error inserting record.")
End If


Example 2: Insert Multiple Product Records

' Example usage - Insert Multiple Products:
Dim productRecords As List
productRecords.Initialize

Dim product1 As Map
product1.Initialize
product1.Put("name", "Keyboard")
product1.Put("price", 49.99)
product1.Put("stock", 50)

Dim product2 As Map
product2.Initialize
product2.Put("name", "Monitor")
product2.Put("price", 199.99)
product2.Put("stock", 20)

productRecords.AddAll(Array(product1, product2))

MagicAPI.InsertMultipleMaps(productRecords, "products")

Wait For MagicAPI_Insertmaps(m As Map, success As Boolean)

If success Then
Log($"Record inserted: ${m}"$)
Else
Log("Error inserting record.")
End If


Notes

  • Both routines provide asynchronous operations, and results are returned via their respective events.
  • Error handling is embedded, and failed operations trigger the appropriate event with a success = False.
  • Ensure the data maps are properly initialized and contain valid column names and values for the target table.


MagicFiles Module Documentation

The MagicFiles module is part of the Magic API library, designed to facilitate file and folder operations on a server via REST API. It supports functionalities such as uploading, downloading, listing, and deleting files or folders, and is compatible with file selection using ContentChooser in B4A.


Initialization

1. Initialize

Initializes the MagicFiles module with the necessary parameters to interact with the server.

Parameters:

  • Callback (Object): The object handling the event callbacks.
  • EventName (String): The name of the event that will be triggered upon completion.
  • urlbase (String): The base URL of the file server.
' Example usage:
Dim magicFiles As MagicFiles
magicFiles.Initialize(Me, "MagicFiles", "https://example.com/api")


File Operations

2. UploadFile

Uploads a file to the server.

Parameters:

  • filedir (String): Directory of the file.
  • filename (String): Name of the file to upload.
Event: <EventName>_UploadResult(Success As Boolean, FileName As String)

' Example usage:
magicFiles.UploadFile(File.DirRootExternal, "test.txt")

Sub MagicFiles_UploadResult(Success As Boolean, FileName As String)
If Success Then
Log($"File ${FileName} uploaded successfully"$)
Else
Log("Error uploading file")
End If
End Sub


3. UploadFileToFolder

Uploads a file to a specific folder on the server.

Parameters:

  • filedir (String): Directory of the file.
  • filename (String): Name of the file to upload.
  • targetFolder (String): Destination folder on the server.
  • newFileName (String): New name for the file on the server.
Event: <EventName>_UploadToFolderResult(Success As Boolean, FileName As String)

' Example usage:
magicFiles.UploadFileToFolder(File.DirRootExternal, "test.txt", "myFolder", "renamed.txt")

Sub MagicFiles_UploadToFolderResult(Success As Boolean, FileName As String)
If Success Then
Log($"File ${FileName} uploaded to folder successfully"$)
Else
Log("Error uploading file to folder")
End If
End Sub


4. UploadFileUri (B4A)

Uploads a file selected using ContentChooser to the server with a custom name.

Parameters:

  • uri (String): URI of the selected file.
  • newFileName (String): Name to save the file as on the server.
Event: <EventName>_UploadResultUri(Success As Boolean, FileName As String)

' Example usage with ContentChooser:
Private Sub Button1_Click
If chooser.IsInitialized = False Then
chooser.Initialize("chooser")
End If
chooser.Show("image/*", "Choose Image")
End Sub

Sub chooser_Result(Success As Boolean, Dir As String, FileName As String)
If Success Then
magicFiles.UploadFileUri(FileName, "uploaded_image.jpg")
Else Log("No file selected")
End If
End Sub

Sub MagicFiles_UploadResultUri(Success As Boolean, FileName As String)
If Success Then
Log($"File ${FileName} uploaded successfully"$)
Else
Log("Error uploading file")
End If
End Sub


5. UploadFileUri2 (B4A)

Uploads a file selected using ContentChooser by directly using its full path.

Parameters:

  • uri (String): URI of the selected file.
Event: <EventName>_UploadResultUri2(Success As Boolean, FileName As String)

' Example usage with ContentChooser:
Private Sub Button1_Click
If chooser.IsInitialized = False Then
chooser.Initialize("chooser")
End If
chooser.Show("[I]/[/I]", "Choose File")
End Sub

Sub chooser_Result(Success As Boolean, Dir As String, FileName As String)
If Success Then
magicFiles.UploadFileUri2(FileName)
Else
Log("No file selected")
End If
End Sub

Sub MagicFiles_UploadResultUri2(Success As Boolean, FileName As String)
If Success Then
Log($"File ${FileName} uploaded successfully with UploadFileUri2"$)
Else
Log("Error uploading file with UploadFileUri2")
End If
End Sub


6. ListFiles

Lists all files available on the server.

Event: <EventName>_ListSuccess(Success As Boolean, ListFiles As List)

' Example usage:
magicFiles.ListFiles

Sub MagicFiles_ListSuccess(Success As Boolean, ListFiles As List)
If Success Then
For Each fileName As String In ListFiles
Log($"File: ${fileName}"$)
Next
Else Log("Error listing files")
End If
End Sub


7. DeleteFile

Deletes a file from the server.

Parameters:

  • fileName (String): Name of the file to delete.
Event: <EventName>_DeleteFileSuccess(Success As Boolean, FileName As String)

' Example usage:
magicFiles.DeleteFile("test.txt")

Sub MagicFiles_DeleteFileSuccess(Success As Boolean, FileName As String)
If Success Then
Log($"File ${FileName} deleted successfully"$)
Else
Log("Error deleting file")
End If
End Sub


8. DeleteAllFiles

Deletes all files from the server.

Event: <EventName>_DeleteAllSuccess(Success As Boolean)

' Example usage:
magicFiles.DeleteAllFiles

Sub MagicFiles_DeleteAllSuccess(Success As Boolean)
If Success Then
Log("All files deleted successfully")
Else
Log("Error deleting all files")
End If
End Sub


Folder Operations

9. CreateFolder

Creates a new folder on the server.

Parameters:

  • FolderName (String): Name of the folder to create.
Event: <EventName>_CreateFolderSuccess(Success As Boolean, FolderName As String)

' Example usage:
magicFiles.CreateFolder("newFolder")

Sub MagicFiles_CreateFolderSuccess(Success As Boolean, FolderName As String)
If Success Then
Log($"Folder ${FolderName} created successfully"$)
Else
Log("Error creating folder")
End If
End Sub


10. MoveFileToFolder

Moves a file to another folder on the server.

Parameters:

  • FileName (String): Name of the file to move.
  • TargetFolder (String): Destination folder.
Event: <EventName>_MoveFileSuccess(Success As Boolean, TargetFolder As String)

' Example usage:
magicFiles.MoveFileToFolder("test.txt", "destinationFolder")

Sub MagicFiles_MoveFileSuccess(Success As Boolean, TargetFolder As String)
If Success Then
Log($"File moved to folder ${TargetFolder} successfully"$)
Else
Log("Error moving file")
End If
End Sub

Important Update for Magic API File Management

We’re introducing an enhanced file and folder management system with the latest version of Magic API! Here's how it works:


File and Folder Operations in Magic API

Default Folder: upload

  • All files and folders you create or interact with will be managed inside a new folder named upload.
  • This folder will be automatically created the first time you upload a file.
Location: The upload folder will be created in the same directory as the files.php script on your server.


Automatic Folder Creation

  • When you add a file to a specific folder, Magic API will automatically create the folder if it doesn’t already exist.
  • This ensures seamless operations, eliminating the need for manual folder setup.

Examples

Uploading a File to the Default Folder

When uploading a file without specifying a folder, it will be stored directly in the upload folder.

' Example - Upload to Default Folder:
MagicFiles.UploadFile(File.DirRootExternal, "example.txt")

Wait For MagicFiles_UploadResult(Success As Boolean, FileName As String)

If Success Then
Log($"File ${FileName} uploaded successfully to the 'upload' folder."$)
Else
Log("Error uploading the file.")
End If


Uploading a File to a Specific Folder

If you specify a folder, Magic API will automatically create it if it doesn’t exist.

' Example - Upload to Specific Folder:
MagicFiles.UploadFileToFolder(File.DirRootExternal, "document.pdf", "tasks", "report.pdf")

Wait For MagicFiles_UploadToFolderResult(Success As Boolean, FileName As String)

If Success Then
Log($"File ${FileName} uploaded successfully to the 'tasks' folder."$)
Else
Log("Error uploading the file.")
End If


Why This Update?

Automated Management: No need to manually create folders. Magic API does it for you!
Simplified Operations: Focus on your app logic while the API handles the backend file structure.
Consistency: All file operations are neatly organized within the upload folder.


Note

  • All file and folder operations (e.g., uploading, deleting, listing) will now occur inside the upload folder for better organization and security.
  • If you interact with a folder that doesn’t exist, it will be created automatically.


? Download Magic API Now

Thank you for your enthusiasm and support. Let the Magic API transform your B4X applications into powerful, connected experiences! ?
 
Last edited:

fernando1987

Active Member
Licensed User
Take advantage and get a 30% discount on any product throughout this month with the code STORECODE30
 

fernando1987

Active Member
Licensed User
*Version 2.0 available*

**Security**


The API prioritizes security and implements various measures to safeguard the integrity and confidentiality of your data:

1. **Authentication**: To access the API, every request must include an API key as a query parameter. This key serves as a unique identifier for the client making the request and grants access control to the API endpoints.

2. **HTTPS**: All communication with the API is encrypted using HTTPS. This ensures that data transmitted between the client and the server remains confidential and protected from unauthorized access.

3. **Input Validation**: The API incorporates robust input validation and sanitization techniques. By doing so, it guards against common security vulnerabilities like SQL injection and cross-site scripting (XSS) attacks. This helps maintain the integrity of the data and protects against malicious input.

For users who have previously obtained an earlier version, they can access the store and log in to their user panel. In the "Recent Orders" section, they will find the option to view their order and download the updated Version 2.0 of the API.
 
Last edited:

peacemaker

Expert
Licensed User
Longtime User
Think about magic for
1) searching records by a part of field's value, ">", "<", ">=", "<="...
2) pagination of the output
 

fernando1987

Active Member
Licensed User
Yes, this API fulfills the following requirements:

1) **Searching records by a part of field's value, ">", "<", ">=", "<="...**: The API has the ability to search for records using comparison operators such as ">", "<", ">=", "<=", and more. This allows you to perform more specific queries and obtain results based on custom conditions.

2) **Pagination of the output**: The API supports pagination of the results, allowing you to retrieve smaller data sets and control the number of records returned in each response. This is useful when dealing with a large number of records and you want to divide them into pages for better navigation and performance.

In summary, this API provides functionalities for searching records by a part of a field's value and for paginating the results, thus meeting the mentioned requirements.

 
Last edited:

fernando1987

Active Member
Licensed User
*Version 3.0 available*

*corrections in the queries by comparison <,>,<=,>=.

*bug fixes and optimization of the api and php file

For users who have previously obtained an earlier version, they can access the store and log in to their user panel. In the "Recent Orders" section, they will find the option to view their order and download the updated Version 3.0 of the API.
 

amorosik

Expert
Licensed User
It's not clear to me what can be done with the library offered
Could you give some practical examples of what can be done using these libraries?

I'm trying to see the DOWNLOAD link but nothing appears, can you check if it's active?
 

fernando1987

Active Member
Licensed User
Hello dear, it is a file written for php8 which allows you to transform any msql database into a json api only with the connection data of the database, it also comes with a library that will facilitate communication with the api... la liberia It is paid and the link will send you to the Liberia purchase page where you can get the library and the php file
It's not clear to me what can be done with the library offered
Could you give some practical examples of what can be done using these libraries?

I'm trying to see the DOWNLOAD link but nothing appears, can you check if it's active?
 

Xfood

Expert
Licensed User

hi friend, your products are really great and very helpful. Will this update be integrated into this project as well?

 

Xfood

Expert
Licensed User
Hi buddy @fernando1987 ,
Have you thought about adding the ability to send and receive a bmp/jpg/png in your magicApi?
in the case, for example, of a user table, where it is entered, Name, Surname, Photo, etc.
transfer the photo, and during a select , download the photo?
Thanks for your awesome bee
 

LucaMs

Expert
Licensed User
Longtime User
it is a file written for php8 which allows you to transform any msql database into a json api only with the connection data of the database
So if you have one of the many free spaces on which to create your own site, which offer a single MySQL DB, you have to write the administrator's name and password in the api.php?
If that were the case, the app user would have indiscriminate access to all the DB tables, while he should be able to access only some and not for all CRUD operations, some in writing but others only in reading.

Can you specify better?
 

fernando1987

Active Member
Licensed User
Hello! Regarding your concern about database security when using Magic API, let me clarify: the database connection credentials (administrator's name and password) should not be included directly in your app's code. These credentials are stored securely in the api.php file, which is uploaded to your server.

Your app, instead of directly accessing the database, communicates with the api.php file through an API key that you define for security. This API key is included in your app's requests to ensure only authorized clients can interact with the API.

Additionally, Magic API works by allowing you to define specific tables and queries . This means you can configure it so users only have access to certain tables or operations (e.g., read-only access for some tables, write access for others). The queries are predefined in the API, so the user does not have direct access to execute arbitrary SQL commands.

This approach ensures:

1. The database credentials remain secure on the server.


2. Users only have access to the specific operations and tables you allow.
 

LucaMs

Expert
Licensed User
Longtime User
(api_key defined in the php file?)

Sorry, but I still don't quite understand how it works.

Can you post a B4XPages page that connects (and what needs to be changed in api.php) and reads all the records in a table?
Even modify a record in another table, having permission.

The examples in this thread are "snippets", parts of code.


Thank you.
 
Last edited:

fernando1987

Active Member
Licensed User
To address your question, I suggest carefully reviewing the first post of the thread in the B4X forum. There, you'll find examples and explanations applicable to B4A, B4I, B4J, and B4XPages, including how to connect and perform operations with MySQL databases using the library.
 

LucaMs

Expert
Licensed User
Longtime User
(api_key defined in the php file?)

Sorry, but I still don't quite understand how it works.
Thanks anyway
 

asales

Expert
Licensed User
Longtime User
As you can change the api.php file, you can put other mesures to secure the code.
I use the enviroment variable to the api_key too.
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…