API Logic and Workflow Integration
Generative natural language rules allow a simple way to extend an API for the developer experience in connecting transaction systems to a workflow.
Join the DZone community and get the full member experience.
Join For FreeGenAI Logic using ApiLogicServer has recently introduced a workflow integration using the n8n.io. The tool has over 250 existing integrations and the developer community supplies prebuilt solutions called templates (over 1000) including AI integrations to build chatbots. GenAI Logic can build the API transaction framework from a prompt and use natural language rules (and rule suggestions) to help get the user started on a complete system. Eventually, most systems require additional tooling to support features like email, push notifications, payment systems, or integration into corporate data stores.
While ApiLogicServer is an existing API platform, writing 250 integration endpoints with all the nuances of security, transformations, logging, and monitoring — not to mention the user interface — would require a huge community effort. ApiLogicServer found the solution with n8n.io (one of many workflow engines on the market). What stands out is that n8n.io offers a community version using a native Node.js solution for local testing (npx n8n) as well as a hosted cloud version.
N8N Workflow
In n8n, you create a Webhook from ApiLogicServer
object which creates a URL that can accept an HTTP GET
, POST
, PUT
, or DELETE
, with added basic authentication (user: admin
, password: p
) to test the webhook. The Convert to JSON
block provides a transformation of the body (a string) into a JSON object using JavaScript. The Switch
block allows routing based on different JSON payloads. The If Inserted
block decides if the Employee was an insert or update (which is passed in the header). The SendGrid
blocks register a SendGrid API key and format an email to send (selecting the email from the JSON using drag-n-drop). Finally, the Respond to Webhook
returns a status code of 200
to the ApiLogicServer event.
Employees, Customers, and Orders are all sent to the same Webhook
Configuration
There are two parts to the configuration. The first is the installation of the workflow engine n8n.io (either on-premise, Docker, or cloud), and then the creation of the webhook
object in the workflow diagram (http://localhost:5678
). This will generate a unique name and path that is passed to the ApiLogicServer project in the config/config.py directory; in this example, a simple basic authorization (user/password).
- Note: In an ApiLogicServer project integration/n8n folder, this sample JSON file is available to import this example into your own n8n project!
Webhook Output
ApiLogicServer Logic and Webhook
The real power of this is the ability to add a business logic rule to trigger the webhook, adding some configuration information (n8n server, port, key, and path plus authorization). So the actual rule (after_flush_row_event
) is called anytime an insert event occurs on an API endpoint. The actual implementation is simply a call to the Python code to post the payload (e.g., requests.post(url=n8n_webhook_url, json=payload, headers=headers)
).
- Configuration to call n8n webhook config/config.py:
wh_scheme = "http"
wh_server = "localhost" # or cloud.n8n.io...
wh_port = 5678
wh_endpoint = "webhook-test" # from n8n Webhook URL
wh_path = "002fa0e8-f7aa-4e04-b4e3-e81aa29c6e69" # from n8n Webhook URL
token = "YWRtaW46cA==" #base64 encode of user/pasword admin:p
N8N_PRODUCER = {"authorization": f"Basic {token}", "n8n_url": \
f'"{wh_scheme}://{wh_server}:{wh_port}/{wh_endpoint}/{wh_path}"'}
# Or enter the n8n_url directly:
N8N_PRODUCER = {"authorization": f"Basic \
{token}","n8n_url":"http://localhost:5678/webhook-test/002fa0e8-f7aa-4e04-b4e3-e81aa29c6e69"}
#N8N_PRODUCER = None # comment out to enable N8N producer
- Call a business rule (
after_flush_row_event
) on the API entity:
def call_n8n_workflow(row: Employee, old_row: Employee, logic_row: LogicRow):
"""
Webhook Workflow: When Employee is inserted = post to n8n webhook
"""
if logic_row.is_inserted():
status = send_n8n_message(logic_row=logic_row)
logic_row.log(status)
Rule.after_flush_row_event(on_class=models.Emploee, calling=call_n8n_workflow)
Declarative Logic (Rules)
ApiLogicServer is an open-source platform based on SQLAlchemy ORM and Flask. The SQLAlchemy provides a hook (before flush
) that allows LogicBank (another open-source tool) to let developers declare "rules." These rules fall into 3 categories: derivations, constraints, and events. Derivations are similar to spreadsheet rules in that they operate on a selected column (cell): formula
, sums
, counts
, and copy
. Constraints operate on the API entity to validate the row and will roll back a multi-table event if the constraint test does not pass. Finally, the events (early
, row
, commit
, and flush
) allow the developer to call "user-defined functions" to execute code during the lifecycle of the API entity. The WebGenAI feature (a chatbot to build applications) was trained on these rules to use natural language prompts (this can also be done in the IDE using Copilot).
Notice that the rules are declared and unordered. New rules can be added or changed and are not actually processed until the state change of the API or attribute is detected. Further, these rules can impact other API endpoints (e.g., sums
, counts
, or formula
) which in turn can trigger constraints and events. Declarative rules can easily be 40x more concise than code.
- Natural language rules generated by WebGenAI:
Use LogicBank to enforce the Check Credit requirement:
1. The Customer's balance is less than the credit limit
2. The Customer's balance is the sum of the Order amount_total where date_shipped is null
3. The Order's amount_total is the sum of the Item amount
4. The Item amount is the quantity * unit_price
5. The Item unit_price is copied from the Product unit_price
Becomes these Rules logic/declary_logic.py
#ApiLogicServer: basic rules - 5 rules vs 200 lines of code:
# logic design translates directly into rules
Rule.constraint(validate=Customer,
as_condition=lambda row: row.Balance <= row.CreditLimit,
error_msg="balance ({round(row.Balance, 2)}) exceeds credit
({round(row.CreditLimit, 2)})")
# adjust iff AmountTotal or ShippedDate or CustomerID changes
Rule.sum(derive=Customer.Balance, as_sum_of=Order.AmountTotal,
where=lambda row: row.ShippedDate is None and row.Ready == True)
# adjust iff Amount or OrderID changes
Rule.sum(derive=Order.AmountTotal, as_sum_of=OrderDetail.Amount)
Rule.formula(derive=OrderDetail.Amount,
as_expression=lambda row: row.UnitPrice * row.Quantity)
# get Product Price (e,g., on insert, or ProductId change)
Rule.copy(derive=OrderDetail.UnitPrice,from_parent=Product.UnitPrice)
SendGrid Email
N8N has hundreds of integration features that follow the same pattern. Add a node to your diagram and attach the input, configure the settings (here, a SendGrid API key is added), and test to see the output. The SendGrid will respond with a messageId
(which can be returned to the caller or stored in a database or Google sheet). Workflows can be downloaded and stored in GitHub or uploaded into the cloud version.
SendGrid input and output (use drag and drop to build email message)
AI Integration: A Chatbot Example
The community contributes workflow "templates" that anyone can pick up and use in their own workflow. One template has the ability to take documents from S3 and feed them to Pinecone (a vector data store). Then, use the AI block to link this to ChatGPT — the template even provides the code to insert into your webpage to make this a seamless end-to-end chatbot integration. Imagine taking your product documentation in Markdown and trying this out on a new website to help users understand how to chat and get answers to questions.
AI workflow to build a chatbot
Summary
GenAI Logic is the new kid on the block. It combines the power of AI chat, natural language rules, and API automation framework to instantly deliver running applications. The source is easily downloaded into a local IDE and the work for the dev team begins. With the API in place, the UI/UX team can use the Ontimze (Angular) framework to "polish" the front end. The developer team can add logic and security to handle the business requirements. Finally, the integration team can build the workflows to meet the business use case requirements.
ApiLogicServer has a Kafka integration for producers and consumers. This extends the need for real-time workflow integration and can produce a Kafka message that a consumer can start the workflow (and log, track, and retry if needed). N8N provides an integration space that gives ApiLogicServer new tools to meet most system integration needs. I have also tested Zapier webhook (a cloud-based solution) which works the same way. Try the WebGenAI for free to get started building apps and logic from prompts.
Opinions expressed by DZone contributors are their own.
Comments