📚 Overview
Swain is a powerful dynamic API engine that automatically generates RESTful endpoints for your data models. It provides automatic CRUD operations, filtering, pagination, and sorting capabilities for any data model.
This SDKs facilitate seamless communication between your Swain generated API and your applications, allowing you to focus on building features rather than boilerplate code.
Auto REST API
Automatic REST API generation
Dynamic Models
Support for dynamic data models
Advanced Filtering
Complex filtering and querying
🔐 Authentication Setup
Your database must include the following two tables at a minimum:
- users – Contains user records.
- api_keys – Stores API keys associated with users.
The api_keys table must include the following columns:
- users_id – Foreign key referencing the
userstable. - key – The actual API key string.
- expires_at – Timestamp indicating key expiration.
After creating the required tables, go to the Auth Mapping section in the Swain platform.
There, you must map the appropriate fields from your users and api_keys tables.
This mapping is mandatory and must be completed before building your API to ensure proper authentication.
If you wish to enable RLS (Row-Level Security), your database must also include these additional tables:
- roles
- role_permissions
- user_roles
- user_permissions
After adding these tables, return to the Auth Mapping section in Swain and complete the RLS-specific mappings. Once this is done, Swain will enforce row-level permission rules in your API automatically.
🛠️ Installation
Install the CrudSQL SDK for your preferred programming language:
# Install Go SDK directly from GitHub
go get github.com/mobixdev/SWAIN-GO_SDK
go get github.com/mobixdev/SWAIN-GO_SDK# Install Python SDK directly from GitHub
pip install git+https://github.com/mobixdev/SWAIN-PYTHON_SDK.git
# Or add to requirements.txt
git+https://github.com/mobixdev/SWAIN-PYTHON_SDK.git@main#egg=crudsql-sdk
# Or using Poetry
poetry add git+https://github.com/mobixdev/SWAIN-PYTHON_SDK.git
# Install TypeScript/JavaScript SDK from GitHub
npm install github:mobixdev/SWAIN-TYPESCRIPT_SDK
# Or using yarn
yarn add github:mobixdev/SWAIN-TYPESCRIPT_SDK
# Or add to package.json
{
"dependencies": {
"@crudsql/sdk": "github:mobixdev/SWAIN-TYPESCRIPT_SDK"
}
}
# Add to composer.json
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/mobixdev/SWAIN-PHP_SDK"
}
],
"require": {
"crudsql/sdk": "dev-main"
}
}
# Then run
composer install
<!-- Add to your pom.xml -->
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.github.mobixdev</groupId>
<artifactId>SWAIN-JAVA_SDK</artifactId>
<version>main-SNAPSHOT</version>
</dependency>
</dependencies>
# Add to pubspec.yaml
dependencies:
crudsql_sdk:
git:
url: https://github.com/mobixdev/SWAIN-DART_SDK
ref: main
# Clone as git submodule
git submodule add https://github.com/mobixdev/SWAIN-CSHARP_SDK libs/crudsql-sdk
# Then add to .csproj
<ItemGroup>
<ProjectReference Include="..\libs\crudsql-sdk\CrudSQL.SDK.csproj" />
</ItemGroup>
🔐 Authentication
Configure authentication using your API key:
import (
"context"
openapi "github.com/mobixdev/CRUDSQL-GO-SDK"
)
// Initialize client with API key
cfg := openapi.NewConfiguration("your-api-key", "https://your-api-host.com/api")
client := openapi.NewAPIClient(cfg)
ctx := context.Background()
// Import the Configuration and your API class
import { Configuration } from './runtime';
import { DynamicApi } from './apis/DynamicApi';
// Initialize the configuration with base URL and API key
const config = new Configuration({
basePath: 'https://your-api-url.com/api', // Replace with your API URL
apiKey: 'your-api-key', // Replace with your API key
});
// Pass the configuration to your API class
const api = new DynamicApi(config);
use OpenAPI\Client\Configuration;
use OpenAPI\Client\Api\DynamicApi;
// 1. Create a configuration instance
$config = Configuration::getDefaultConfiguration();
// 2. Set the API base URL (e.g., 'https://your-api.com/api')
$config->setHost('https://your-api.com/api');
// 3. Set the API key
$config->setApiKey('your_api_key_here');
// 4. Create the API instance with your config
$apiInstance = new DynamicApi(null, $config);
// Import the necessary classes
import org.openapitools.client.ApiClient;
import org.openapitools.client.Configuration;
import org.openapitools.client.api.DynamicApi;
// Create and configure the ApiClient
ApiClient apiClient = Configuration.getDefaultApiClient();
apiClient.setBasePath("https://your-api-url.com"); // Set your API base URL
apiClient.setApiKey("YOUR_API_KEY"); // Set your API key
// Pass the configured ApiClient to your API class
DynamicApi api = new DynamicApi(apiClient);
// Create and configure the ApiClient
final apiKeyAuth = ApiKeyAuth()
..apiKey = 'YOUR_API_KEY_HERE';
final apiClient = ApiClient(
basePath: 'https://your-api-url.com/api',
authentication: apiKeyAuth,
);
// Pass the configured ApiClient to your API class
final api = DynamicApi(apiClient);
var config = new Configuration();
//configure the base URL and API key
config.BasePath = "https://your-api-url.com/api";
config.AddApiKey("your-api-key");
// Create the API client with the configuration
var api = new DynamicApi(config);
import openapi_client
# Replace 'your-api-key-value' with your actual API key
configuration = openapi_client.Configuration(
host="https://your-api-url.com/api",
api_key={"ApiKeyAuth": "your-api-key-value"}
)
api_client = openapi_client.ApiClient(configuration)
# use api_client with your API classes, e.g.:
dynamic_api = openapi_client.DynamicApi(api_client)
➕ Create Entity
/{model}
Create a new entity of the specified model type.
// Prepare the user data as a map
user := map[string]interface{}{
"username": "johndoe",
"email": "john@example.com",
"age" : 30,
// Example of a relation, e.g. addresses
"addresses": []map[string]interface{}{
{
"city": "New York",
"country": "USA",
},
},
// Add other fields as required by your user model
}
// Create the user
ctx := context.Background()
req := client.DynamicAPI.Create(ctx, "users").Entity(user)
resp, httpResp, err := req.Execute()
if err != nil {
log.Fatalf("Error creating user: %v", err)
}
defer httpResp.Body.Close()
fmt.Printf("Created user: %+v\n", resp)
async function addUser() {
const request = {
model: 'user', // The model name as defined in your backend
entity: {
name: 'Alice',
email: 'alice@example.com',
// Example of a relation, e.g. addresses
addresses: [
{
city: 'Wonderland',
country: 'Fantasy'
}
],
}
};
try {
const result = await api.Create(request);
console.log('User created:', result);
} catch (error) {
console.error('Error creating user:', error);
}
}
$userData = [
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => 'securepassword'
'addresses' => [
[
'city' => 'New York',
'country' => 'USA'
]
],
];
$model = 'user'; // The model name as defined in your API
$payload = $userData;
try {
$result = $apiInstance->modelPost($model, $payload);
print_r($result); // Success response
} catch (Exception $e) {
echo 'Exception when creating user: ', $e->getMessage(), PHP_EOL;
}
Map<String, Object> user = new HashMap<> ();
user.put("name", "John Doe");
user.put("email", "john@example.com");
// Add addresses as a relation
List<Map<String, Object>> addresses = new ArrayList<>();
Map<String, Object> address = new HashMap<>();
address.put("city", "New York");
address.put("country", "USA");
addresses.add(address);
user.put("addresses", addresses);
try {
Object createdUser = api.Create("user", user);
System.out.println("Created user: " + createdUser);
} catch (ApiException e) {
e.printStackTrace();
}
// Example user data as a Map
final userData = {
'name': 'John Doe',
'email': 'john@example.com',
'password': 'securePassword123',
// Example of a relation, e.g. addresses
'addresses': [
{
'city': 'New York',
'country': 'USA',
},
],
// Add other fields as required by your user model
'age': 30,
};
final createdUser = await dynamicApi.Create('user', userData);
string modelName = "user";
// The user object as a dynamic or strongly-typed object
var user = new {
username = "johndoe",
email = "john@example.com",
password = "securepassword"
addrresses = new[] {
new {
city = "New York",
country = "USA"
}
},
// Add other fields as required by your user model
age = 30
};
// Create the user
var result = api.Create(modelName, user);
# 1. Prepare the user data as a dictionary
user_data = {
"username": "newuser",
"email": "newuser@example.com",
"password": "securepassword"
"addresses": [
{
"city": "New York",
"country": "USA"
}
],
# Add other fields as required by your user model
"age": 30,
}
# 2. Call the Create method
result = dynamic_api.Create("User", user_data)
print(result)
📖 Read Entity by ID
/{model}/{id}
Retrieve a single entity by its ID.
model := "users" // or your actual model name
id := "123" // the ID of the user/entity
ctx := context.Background()
req := client.DynamicAPI.GetById(ctx, model, id)
entity, httpResp, err := req.Execute()
if err != nil {
log.Fatalf("Error fetching entity: %v", err)
}
defer httpResp.Body.Close()
fmt.Printf("Fetched entity: %+v\n", entity)
async function readEntityByIdExample() {
const model = 'user';
const entityId = 'fc55-tyrpem4-44jkkt'; // Replace with a real ID
const byId = await api.GetById({ model, id: entityId });
console.log('Read by ID:', byId);
}
$id = 'fc55-tyrpem4-44jkkt'; // Replace with a real ID
if ($id) {
$byId = $api->GetById('User', $id);
echo "Read by ID:\n";
print_r($byId);
}
String model = "user"; // Replace with your model name
String id = "123"; // Replace with the entity ID you want to fetch
try {
Object user = api.GetById(model, id);
System.out.println("Fetched entity: " + user);
} catch (Exception e) {
e.printStackTrace();
}
final result = await api.GetById('user', '123');
print('Entity: ${result}');
var entityId = "123";
var getResult = api.GetById("users", entityId);
# Replace with your model name and the entity ID you want to fetch
model_name = "User"
entity_id = "12345"
# Fetch the entity by ID
entity = dynamic_api.GetById(model_name, entity_id)
print(entity)
📚 Read All Entities
/{model}
Get a list of entities with pagination and sorting support.
page := int32(1) // Page number
pageSize := int32(20) // Items per page
req := client.DynamicAPI.GetAll(ctx, "users").Page(page).PageSize(pageSize)
resp, httpResp, err := req.Execute()
if err != nil {
log.Fatalf("Error fetching users: %v", err)
}
defer httpResp.Body.Close()
fmt.Printf("Users: %+v\n", resp)
async function getAllUsers() {
const request = {
model: 'user', // Replace with your model name if different
page: 1, // Page number (1-based)
pageSize: 20, // Number of users per page
};
try {
const result = await api.GetAll(request);
console.log('Users:', result);
} catch (error) {
console.error('Error fetching users:', error);
}
}
$model = 'user'; // Replace with your model name
$page = 1; // Page number
$pageSize = 20; // Items per page
try {
// 4. Get all users with pagination
$result = $apiInstance->GetAll($model, $page, $pageSize);
print_r($result); // The paginated list of users
} catch (Exception $e) {
echo 'Exception when calling GetAll: ', $e->getMessage(), PHP_EOL;
}
String model = "user"; // Replace with your actual model name
Integer page = 1; // Page number (start from 1)
Integer pageSize = 20; // Items per page
try {
QueryFilterResponse response = api.GetAll(model, page, pageSize);
System.out.println("Users: " + response);
} catch (Exception e) {
e.printStackTrace();
}
final int page = 1;
final int pageSize = 20;
final usersResponse = await dynamicApi.GetAll(
'user',
page: page,
pageSize: pageSize,
);
print(usersResponse);
string modelName = "user"; // or "users" if that's your model name
int page = 1;
int pageSize = 20;
var result = api.GetAll(modelName, page, pageSize);
# Get all users, page 1, 20 users per page
result = dynamic_api.GetAll("User", page=1, page_size=20)
print(result)
🔍 Read with Filters
/{model}/filter
Filter entities using complex conditions including field expressions, logical operations, and relationship filtering.
// Complex filtering example
filter := openapi.NewQueryFilter()
filter.SetExpressions([]map[string]interface{}{
{
"operator": "AND",
"expressions": []map[string]interface{}{
{
"field": "status",
"operator": "eq",
"value": "active",
},
{
"field": "age",
"operator": "gt",
"value": 18,
},
},
},
})
filter.SetSort([]openapi.QuerySortSpec{
{
Field: "createdAt",
Direction: "desc",
},
})
filtered, _, err := client.DynamicAPI.GetWhere(ctx, "users").
Where(*filter).
Page(1).
PageSize(10).
Execute()
async function filterAndSortUsers() {
const filter = {
operator: 'AND',
expressions: [
{ field: 'status', operator: 'eq', value: 'active' },
{ field: 'age', operator: 'gte', value: 18 }
],
sort: [
{ field: 'createdAt', direction: 'desc' }
]
};
const request = {
model: 'user',
filter,
page: 1,
pageSize: 20,
};
const result = await api.GetWhere(request);
console.log(result);
}
$filter = new QueryFilter([
'operator' => 'OR',
'expressions' => [
[
'field' => 'status',
'operator' => 'eq',
'value' => 'active'
],
[
'field' => 'age',
'operator' => 'gte',
'value' => 18
]
],
'sort' => [
new QuerySortSpec([
'field' => 'name',
'direction' => 'asc'
])
]
]);
// Call GetWhere
$model = 'user';
$page = 1;
$pageSize = 10;
try {
$result = $apiInstance->GetWhere($model, $filter, $page, $pageSize);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling GetWhere: ', $e->getMessage(), PHP_EOL;
}
QueryQueryFilter filter = new QueryQueryFilter();
Map<String, Object> expr = new HashMap<>();
expr.put("field", "age");
expr.put("operator", "gte");
expr.put("value", 18);
filter.addExpressionsItem(expr);
QueryFilterResponse filtered = api.GetWhere('user', filter, 1, 10, null);
System.out.println("Filtered: " + filtered);
// Build filter expressions (AND condition)
List<Object> expressions = new ArrayList<>();
// Example: field "status" == "active"
Map<String, Object> expr1 = new HashMap<>();
expr1.put("field", "status");
expr1.put("operator", "eq");
expr1.put("value", "active");
expressions.add(expr1);
// Example: field "age" >= 18
Map<String, Object> expr2 = new HashMap<>();
expr2.put("field", "age");
expr2.put("operator", "gte");
expr2.put("value", 18);
expressions.add(expr2);
// Wrap with AND operator (if needed for nested logic)
Map<String, Object> andExpr = new HashMap<>();
andExpr.put("operator", "AND");
andExpr.put("expressions", expressions);
List<Object> rootExpressions = new ArrayList<>();
rootExpressions.add(andExpr);
QueryFilter filter = new QueryFilter();
filter.setExpressions(rootExpressions);
// Add sorting: sort by "name" ascending
QuerySortSpec sortSpec = new QuerySortSpec().field("name").direction("asc");
filter.setSort(Collections.singletonList(sortSpec));
try {
QueryFilterResponse response = api.GetWhere("user", filter, 1, 20);
System.out.println("Filtered and sorted users: " + response);
} catch (Exception e) {
e.printStackTrace();
}
final expression = {
'operator': 'AND',
'expressions': [
{
'field': 'age',
'operator': 'eq',
'value': '18',
},
{
'field': 'active',
'operator': 'eq',
'value': true,
},
],
};
final sort = [
QuerySortSpec(field: 'createdAt', direction: 'desc'),
];
final filter = QueryFilter(
expressions: [expression],
sort: sort,
);
final result = await dynamicApi.GetWhere(
'user',
filter,
page: 1,
pageSize: 20,
);
print(result);
var orExpression = new Dictionary<string, object>
{
{ "operator", "OR" },
{ "expressions", new List<object>
{
new Dictionary<string, object>
{
{ "field", "username" },
{ "operator", "eq" },
{ "value", "alice" }
},
new Dictionary<string, object>
{
{ "field", "email" },
{ "operator", "eq" },
{ "value", "bob@example.com" }
}
}
}
};
// Add sort: sort by "createdAt" descending
var sortSpec = new List<QuerySortSpec>
{
new QuerySortSpec(direction: "desc", field: "createdAt")
};
// Build QueryFilter
var filter = new QueryFilter(
expressions: new List<object> { orExpression },
sort: sortSpec
);
// Call GetWhere (with pagination if needed)
var result = api.GetWhere("user", filter, page: 1, pageSize: 20);
# Example: Get users where (email == "a@b.com" OR username == "john"), sorted by createdAt descending
query_filter = QueryFilter(
expressions=[
{
"operator": "OR",
"expressions": [
{"field": "email", "operator": "eq", "value": "a@b.com"},
{"field": "username", "operator": "eq", "value": "john"},
],
}
],
sort=[
QuerySortSpec(field="createdAt", direction="desc")
]
)
result = dynamic_api.GetWhere("User", query_filter, page=1, page_size=10)
print(result)
✏️ Update Entity by ID
/{model}/{id}
Update an existing entity by its ID.
model := "users" // or your actual model name
id := "123" // the ID of the entity you want to update
// Prepare the updated fields
update := map[string]interface{}{
"email": "newemail@example.com",
// Add other fields to update as needed
}
ctx := context.Background()
req := client.DynamicAPI.UpdateById(ctx, model, id).Entity(update)
resp, httpResp, err := req.Execute()
if err != nil {
log.Fatalf("Error updating entity: %v", err)
}
defer httpResp.Body.Close()
fmt.Printf("Updated entity: %+v\n", resp)
}
async function updateUserById(userId: string) {
const request = {
model: 'user', // Replace with your model name
id: userId, // The ID of the user to update
entity: {
name: 'Updated Name',
email: 'updated.email@example.com',
// ...other fields to update
}
};
try {
const result = await api.UpdateById(request);
console.log('User updated:', result);
} catch (error) {
console.error('Error updating user:', error);
}
}
$model = 'user'; // Replace with your model name
$id = '123'; // Replace with the actual entity ID
// Data to update
$updateData = [
'name' => 'Jane Doe',
'email' => 'jane@example.com'
// Add other fields as needed
];
try {
// 4. Update the entity by ID
$result = $apiInstance->UpdateById($model, $id, $updateData);
print_r($result); // Updated entity data
} catch (Exception $e) {
echo 'Exception when calling UpdateById: ', $e->getMessage(), PHP_EOL;
}
String model = "user"; // Replace with your model name
String id = "123"; // Replace with the entity ID you want to update
// Prepare the updated entity data
Map<String, Object> updatedData = new HashMap<>();
updatedData.put("name", "Jane Doe");
updatedData.put("email", "jane@example.com");
// Add other fields as needed
try {
Object updatedEntity = api.UpdateById(model, id, updatedData);
System.out.println("Updated entity: " + updatedEntity);
} catch (Exception e) {
e.printStackTrace();
}
final String userId = '123'; // The ID of the user you want to update
final updatedUserData = {
'name': 'Jane Doe',
'email': 'jane.doe@example.com',
// Add other fields you want to update
};
final updatedUser = await dynamicApi.UpdateById(
'user', // model name
userId, // entity ID
updatedUserData, // updated data as a Map
);
print('Updated user: $updatedUser');
// Specify the model name and entity ID
string modelName = "user"; // or your actual model name
string entityId = "12345"; // the ID of the entity you want to update
// Prepare the updated data (fields you want to change)
var updatedData = new {
email = "newemail@example.com",
status = true
// add other fields as needed
};
// Update the entity
var result = api.UpdateById(modelName, entityId, updatedData);
# Specify the model name and entity ID
model_name = "User"
entity_id = "12345" # Replace with the actual ID
# Prepare the updated data
updated_data = {
"email": "newemail@example.com",
"username": "newusername"
# Add other fields to update as needed
}
# Call UpdateById
result = dynamic_api.UpdateById(model_name, entity_id, updated_data)
print(result)
✏️ Update Many Entities
/{model}/filter
Update multiple entities that match the provided query expression.
expressions := []map[string]interface{}{
{
"operator": "AND",
"expressions": []map[string]interface{}{
{
"field": "status",
"operator": "eq",
"value": "pending",
},
{
"field": "age",
"operator": "gt",
"value": 18,
},
},
},
}
// Fields to update
updateData := map[string]interface{}{
"status": "active",
}
// Create the payload
payload := openapi.NewApiUpdateFilterPayload()
payload.SetExpressions(expressions)
payload.SetUpdateData(updateData)
ctx := context.Background()
req := client.BulkOperationsAPI.UpdateWhere(ctx, model).Filter(*payload)
resp, httpResp, err := req.Execute()
if err != nil {
log.Fatalf("Error updating entities: %v", err)
}
defer httpResp.Body.Close()
fmt.Printf("Update result: %+v\n", resp)
async function updateUsersByFilter() {
const filter = {
expressions: [
{
operator: 'OR',
expressions: [
{ field: 'status', operator: 'eq', value: 'pending' },
{ field: 'age', operator: 'lt', value: 18 }
]
}
],
updateData: {
status: 'inactive'
}
};
const request = {
model: 'user',
filter
};
try {
const result = await api.UpdateWhere(request);
console.log('Update result:', result);
} catch (error) {
console.error('Error updating users:', error);
}
}
$filterPayload = new ApiUpdateFilterPayload([
'operator' => 'OR',
'expressions' => [
[
'field' => 'status',
'operator' => 'eq',
'value' => 'pending'
],
[
'field' => 'age',
'operator' => 'lt',
'value' => 18
]
],
'update_data' => [
'status' => 'inactive'
]
]);
// Call UpdateWhere
$model = 'user'; // Replace with your model name
try {
$result = $apiInstance->UpdateWhere($model, $filterPayload);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling UpdateWhere: ', $e->getMessage(), PHP_EOL;
}
List<Object> orExpressions = new ArrayList<>();
Map<String, Object> expr1 = new HashMap<>();
expr1.put("field", "status");
expr1.put("operator", "eq");
expr1.put("value", "pending");
orExpressions.add(expr1);
Map<String, Object> expr2 = new HashMap<>();
expr2.put("field", "age");
expr2.put("operator", "lt");
expr2.put("value", 18);
orExpressions.add(expr2);
Map<String, Object> orGroup = new HashMap<>();
orGroup.put("operator", "OR");
orGroup.put("expressions", orExpressions);
// Prepare update data
Map<String, Object> updateData = new HashMap<>();
updateData.put("status", "inactive");
// Build payload
ApiUpdateFilterPayload payload = new ApiUpdateFilterPayload();
payload.setExpressions(Collections.singletonList(orGroup));
payload.setUpdateData(updateData);
try {
api.UpdateWhere("user", payload); // Replace "user" with your model name if needed
System.out.println("Entities updated successfully.");
} catch (ApiException e) {
e.printStackTrace();
}
final orExpression = {
'operator': 'OR',
'expressions': [
{
'field': 'role',
'operator': 'eq',
'value': 'admin',
},
{
'field': 'active',
'operator': 'eq',
'value': false,
},
],
};
// Define the data to update
final updateData = {
'verified': true,
};
// Build the payload
final payload = ApiUpdateFilterPayload(
expressions: [orExpression],
updateData: updateData,
);
// Call the update method
final result = await dynamicApi.UpdateWhere(
'user', // model name
payload,
);
var orExpression = new Dictionary<string, object>
{
{ "operator", "OR" },
{ "expressions", new List<object>
{
new Dictionary<string, object>
{
{ "field", "username" },
{ "operator", "eq" },
{ "value", "alice" }
},
new Dictionary<string, object>
{
{ "field", "email" },
{ "operator", "eq" },
{ "value", "bob@example.com" }
}
}
}
};
// Specify the fields to update
var updateData = new Dictionary<string, object>
{
{ "status", "active" }
};
// Build the update filter payload
var updatePayload = new ApiUpdateFilterPayload(
expressions: new List<object> { orExpression },
updateData: updateData
);
// Call UpdateWhere
var result = api.UpdateWhere("user", updatePayload);
# Build the filter payload with OR condition
update_filter = ApiUpdateFilterPayload(
expressions=[
{
"operator": "OR",
"expressions": [
{"field": "email", "operator": "eq", "value": "a@b.com"},
{"field": "username", "operator": "eq", "value": "john"},
],
}
],
updateData={
"status": "active" # Example: set status to "active"
}
)
# Call UpdateWhere on the DynamicApi instance
result = dynamic_api.UpdateWhere("User", update_filter)
print(result)
🗑️ Delete Entity by ID
/{model}/{id}
Delete an entity by its ID.
// Delete user by ID
_, _, err := client.DynamicAPI.DeleteById(ctx, "users", "123").Execute()
if err != nil {
log.Fatal(err)
}
fmt.Println("User deleted successfully")
async function deleteEntityByIdExample() {
const model = 'user';
const entityId = 'ufr673-uu382d'; // Replace with a real ID
const deleted = await api.DeleteById({ model, id: entityId });
console.log('Deleted by ID:', deleted);
}
$deleted = $api->DeleteById('User', '123');
echo "Deleted by ID:\n";
print_r($deleted);
//delete user by ID
api.DeleteById('user', entityId);
System.out.println("Deleted by ID: " + entityId);
final deleted = await api.DeleteById('user', '123');
print('Delete result: ${deleted}');
var deleteResult = api.DeleteById("users", "123");
Console.WriteLine($"Deleted entity with ID: {deleteResult}");
model_name = "User"
entity_id = "12345"
result = dynamic_api.DeleteById(model_name, entity_id)
print(result)
🗑️ Delete Many Entities
/{model}/filter
Delete multiple entities that match the provided query expression.
// Delete all inactive users
filter := openapi.NewApiFilterPayload()
filter.SetExpressions([]map[string]interface{}{
{
"field": "status",
"operator": "eq",
"value": "inactive",
},
})
result, _, err := client.DynamicAPI.DeleteWhere(ctx, "users").
Filter(*filter).
Execute()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Deleted %d records\n", result["affected"])
async function deleteInactiveUsers() {
const request = {
model: 'user',
filter: {
expressions: [
{ field: 'status', operator: 'eq', value: 'inactive' }
]
}
};
try {
const result = await api.DeleteWhere(request);
console.log('Delete result:', result);
} catch (error) {
console.error('Error deleting users:', error);
}
$filter = new ApiFilterPayload([
'expressions' => [
[
'field' => 'status',
'operator' => 'eq',
'value' => 'inactive'
]
]
]);
$model = 'user';
try {
$result = $apiInstance->DeleteWhere($model, $filter);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling DeleteWhere: ', $e->getMessage(), PHP_EOL;
}
// Build filter: status == "inactive"
Map<String, Object> condition = new HashMap<>();
condition.put("field", "status");
condition.put("operator", "eq");
condition.put("value", "inactive");
ApiFilterPayload filter = new ApiFilterPayload();
filter.setExpressions(Collections.singletonList(condition));
try {
api.DeleteWhere("user", filter);
System.out.println("Entities deleted successfully.");
} catch (ApiException e) {
e.printStackTrace();
}
final filter = ApiFilterPayload(
expressions: [
{
'type': 'FieldExpression',
'field': 'active',
'operator': 'eq',
'value': false,
},
],
);
final result = await dynamicApi.DeleteWhere(
'user', // model name
filter,
);
print(result);
// Build the filter condition: status == "inactive"
var condition = new Dictionary<string, object>
{
{ "field", "status" },
{ "operator", "eq" },
{ "value", "inactive" }
};
// Create the filter payload
var filter = new ApiFilterPayload(new List<object> { condition });
// Delete entities matching the filter
var result = api.DeleteWhere("user", filter);
# Build the filter payload with one condition
filter_payload = ApiFilterPayload(
expressions=[
{"field": "status", "operator": "eq", "value": "inactive"}
]
)
# Call DeleteWhere on the DynamicApi instance
result = dynamic_api.DeleteWhere("User", filter_payload)
print(result)
🔌 WebSocket Events
Listen to real-time events for create, update, and delete operations on your models.
Listen to Specific Events
// Listen to created events
err := client.DynamicAPI.Listen(ctx, "users", "created",
func(event, model string, data interface{}) {
fmt.Printf("New user created: %v\n", data)
})
if err != nil {
log.Fatal(err)
}
// Listen to updated events
err = client.DynamicAPI.Listen(ctx, "users", "updated",
func(event, model string, data interface{}) {
fmt.Printf("User updated: %v\n", data)
})
if err != nil {
log.Fatal(err)
}
// Listen to deleted events
err = client.DynamicAPI.Listen(ctx, "users", "deleted",
func(event, model string, data interface{}) {
fmt.Printf("User deleted: %v\n", data)
})
if err != nil {
log.Fatal(err)
}
// Listen to created events
api.Listen('users', 'created', (event, model, data) => {
console.log(`New user created:`, data);
});
// Listen to updated events
api.Listen('users', 'updated', (event, model, data) => {
console.log(`User updated:`, data);
});
// Listen to deleted events
api.Listen('users', 'deleted', (event, model, data) => {
console.log(`User deleted:`, data);
});
// Listen to created events
$apiInstance->Listen('users', 'created', function($event, $model, $data) {
echo "New user created: " . json_encode($data) . "\n";
});
// Listen to updated events
$apiInstance->Listen('users', 'updated', function($event, $model, $data) {
echo "User updated: " . json_encode($data) . "\n";
});
// Listen to deleted events
$apiInstance->Listen('users', 'deleted', function($event, $model, $data) {
echo "User deleted: " . json_encode($data) . "\n";
});
// Listen to created events
api.Listen("users", "created",
(event, model, data) -> {
System.out.println("New user created: " + data);
});
// Listen to updated events
api.Listen("users", "updated",
(event, model, data) -> {
System.out.println("User updated: " + data);
});
// Listen to deleted events
api.Listen("users", "deleted",
(event, model, data) -> {
System.out.println("User deleted: " + data);
});
// Listen to created events
dynamicApi.Listen('users', 'created', (event, model, data) {
print('New user created: $data');
});
// Listen to updated events
dynamicApi.Listen('users', 'updated', (event, model, data) {
print('User updated: $data');
});
// Listen to deleted events
dynamicApi.Listen('users', 'deleted', (event, model, data) {
print('User deleted: $data');
});
// Listen to created events
api.Listen("users", "created",
(eventType, model, data) =>
{
Console.WriteLine($"New user created: {data}");
});
// Listen to updated events
api.Listen("users", "updated",
(eventType, model, data) =>
{
Console.WriteLine($"User updated: {data}");
});
// Listen to deleted events
api.Listen("users", "deleted",
(eventType, model, data) =>
{
Console.WriteLine($"User deleted: {data}");
});
// Listen to created events
dynamic_api.Listen("users", "created",
(eventType, model, data) =>
{
Console.WriteLine($"New user created: {data}");
});
// Listen to updated events
dynamic_api.Listen("users", "updated",
(eventType, model, data) =>
{
Console.WriteLine($"User updated: {data}");
});
// Listen to deleted events
dynamic_api.Listen("users", "deleted",
(eventType, model, data) =>
{
Console.WriteLine($"User deleted: {data}");
});
Event Payload Example
{
"event": "created",
"model": "users",
"data": {
"id": "456",
"name": "Jane Doe",
"email": "jane@example.com",
"age": 28,
"createdAt": "2025-05-29T10:30:00Z"
}
}