🔌 API Tools
🎯 Mục tiêu bài học
Sau bài học này, bạn sẽ:
✅ Hiểu API Tool Architecture cho AI Agents
✅ Xây dựng Generic API Tool với domain whitelist
✅ Tạo CRM Tool (HubSpot integration)
✅ Build Project Management Tool (Trello)
✅ Implement Multi-Channel Notification Tool
✅ Áp dụng Error Handling và API Security
Cho phép agents gọi external APIs, integrate third-party services, và thực hiện real-world actions.
🔍 API Tool Architecture
Checkpoint
API Tool Architecture gồm những layers nào? Tại sao cần API Tool Manager?
🌐 Generic API Tool
1// Tool: api_request 2// Description: "Make HTTP requests to APIs. Specify URL, method, headers, body"34// Code node: API call wrapper5const config = {6 url: $json.url,7 method: $json.method || "GET",8 headers: $json.headers || {},9 body: $json.body || null10};1112// Safety checks13const allowedDomains = [14 "api.hubspot.com",15 "api.trello.com", 16 "api.notion.com",17 "slack.com"18];1920const domain = new URL(config.url).hostname;21if (!allowedDomains.some(d => domain.includes(d))) {22 return { json: { error: `Domain ${domain} not in allowed list` } };23}2425// Execute via HTTP Request node26return { json: config };Checkpoint
Tại sao Generic API Tool cần domain whitelist? Cách implement safety checks cho API calls?
🛠️ CRM Tool: HubSpot
1// Tool: crm_manager2// Description: "Manage contacts, deals, and companies in HubSpot CRM"34// Sub-tools:5const crmOperations = {6 searchContacts: {7 method: "POST",8 url: "https://api.hubapi.com/crm/v3/objects/contacts/search",9 body: {10 filterGroups: [{11 filters: [{12 propertyName: "email",13 operator: "EQ",14 value: $json.email15 }]16 }]17 }18 },19 20 createContact: {21 method: "POST",22 url: "https://api.hubapi.com/crm/v3/objects/contacts",23 body: {24 properties: {25 email: $json.email,26 firstname: $json.firstName,27 lastname: $json.lastName,28 company: $json.company29 }30 }31 },32 33 createDeal: {34 method: "POST",35 url: "https://api.hubapi.com/crm/v3/objects/deals",36 body: {37 properties: {38 dealname: $json.dealName,39 amount: $json.amount,40 pipeline: "default",41 dealstage: "appointmentscheduled"42 }43 }44 }45};4647return { json: crmOperations[$json.operation] };Checkpoint
CRM Tool hỗ trợ những operations nào? Làm sao để Agent biết khi nào dùng searchContacts vs createContact?
📋 Project Management Tool: Trello
1// Tool: project_manager2// Description: "Create and manage Trello cards and boards"34const trelloOps = {5 createCard: {6 url: `https://api.trello.com/1/cards`,7 method: "POST",8 params: {9 key: process.env.TRELLO_KEY,10 token: process.env.TRELLO_TOKEN,11 idList: $json.listId,12 name: $json.title,13 desc: $json.description,14 due: $json.dueDate15 }16 },17 18 listCards: {19 url: `https://api.trello.com/1/lists/${$json.listId}/cards`,20 method: "GET",21 params: {22 key: process.env.TRELLO_KEY,23 token: process.env.TRELLO_TOKEN24 }25 },26 27 moveCard: {28 url: `https://api.trello.com/1/cards/${$json.cardId}`,29 method: "PUT",30 params: {31 key: process.env.TRELLO_KEY,32 token: process.env.TRELLO_TOKEN,33 idList: $json.targetListId34 }35 }36};Checkpoint
Trello Tool hỗ trợ những operations nào? API credentials được quản lý như thế nào?
📢 Notification Tool
1// Tool: notify2// Description: "Send notifications via Slack, email, or SMS"34// Route based on channel5const channel = $json.channel;67switch (channel) {8 case "slack":9 // Slack node: Post Message10 return {11 json: {12 channel: $json.slackChannel,13 text: $json.message,14 blocks: [{15 type: "section",16 text: { type: "mrkdwn", text: $json.message }17 }]18 }19 };20 21 case "email":22 // Gmail node: Send23 return {24 json: {25 to: $json.to,26 subject: $json.subject,27 body: $json.message28 }29 };30 31 case "telegram":32 // Telegram node: Send Message33 return {34 json: {35 chatId: $json.chatId,36 text: $json.message37 }38 };39}Checkpoint
Multi-channel Notification Tool routing dựa trên gì? Mỗi channel cần những parameters khác nhau nào?
⚡ Multi-API Agent Example
1// Agent with multiple API tools2const agentPrompt = `3You are an operations assistant with access to multiple tools:41. crm_manager - Search/create contacts and deals in HubSpot52. project_manager - Create/manage tasks in Trello63. notify - Send Slack/email notifications78When given a task:91. Break it into steps102. Use appropriate tools113. Confirm each action result124. Report summary when done1314Always ask for confirmation before sending emails.15`;Checkpoint
Multi-API Agent orchestrate nhiều APIs như thế nào? Agent quyết định thứ tự gọi API dựa trên gì?
🛡️ Error Handling & Security
1// Code node: API error handler2const response = $json;34if (response.statusCode >= 400) {5 const errorMsg = {6 400: "Bad request - check input parameters",7 401: "Authentication failed - check API credentials",8 403: "Access denied - insufficient permissions",9 404: "Resource not found",10 429: "Rate limited - wait and retry",11 500: "Server error - try again later"12 };13 14 return {15 json: {16 success: false,17 error: errorMsg[response.statusCode] || `Error: ${response.statusCode}`,18 details: response.body19 }20 };21}2223return { json: { success: true, data: response.body } };- Domain whitelist: Chỉ cho phép approved domains
- Credential isolation: API keys trong n8n credentials, không trong prompts
- Rate limiting: Respect API rate limits
- Confirmation: Ask before destructive actions (delete, send email)
- Audit trail: Log mọi API calls agent thực hiện
Checkpoint
Cách xử lý HTTP error codes trong API Tool? Những biện pháp bảo mật nào cần áp dụng?
📚 Bài tập thực hành
- Create CRM tool (search contacts, create deals)
- Build project management tool (Trello/Notion tasks)
- Create multi-channel notification tool
- Build agent kết hợp 3+ API tools cho complex task
Checkpoint
Bạn đã build được multi-API agent chưa? Agent có thể orchestrate nhiều API calls hiệu quả không?
🚀 Bài tiếp theo
Bài tiếp theo: Speech-to-Text →
