API Integration Guide: Kết Nối Hệ Thống & Tự Động Hóa Quy Trình
REST, GraphQL, Webhooks – Best Practices for Developers
Mở Bài
“Hệ thống của chúng tôi không nói chuyện được với nhau.”
Đây là vấn đề phổ biến:
- CRM (HubSpot) có customer data
- E-commerce (Shopify) có order data
- Accounting (Xero) cần invoice data
- Warehouse cần shipping data
- Nhân viên manually copy-paste data giữa các systems = 10 giờ/tuần lãng phí
Solution: API Integration
API (Application Programming Interface) = Cách các software nói chuyện với nhau
Benefits:
- ✅ Automation: Data tự động sync (no manual entry)
- ✅ Real-time: Changes reflect instantly (not batch updates)
- ✅ Accuracy: Eliminate human errors (typos, duplicates)
- ✅ Scale: Handle 1,000 orders/day same effort as 10 orders/day
- ✅ Efficiency: Save 10-50 giờ/tuần (ROI huge!)
Trong bài viết này, bạn sẽ học:
- ✅ API types (REST, GraphQL, SOAP, webhooks)
- ✅ Integration patterns & best practices
- ✅ Authentication & security
- ✅ Error handling & monitoring
- ✅ Real-world examples (Shopify + CRM + accounting)
- ✅ Tools & frameworks (Zapier vs custom code)
1. API Types – REST vs GraphQL vs Webhooks
REST API (Most Popular)
REST = Representational State Transfer
Characteristics:
- HTTP methods: GET, POST, PUT, DELETE
- Resource-based URLs (
/api/products/123) - Stateless (each request independent)
- JSON response (usually)
Example Request:
GET https://api.example.com/products/123
Authorization: Bearer YOUR_API_KEY
Example Response:
{
"id": 123,
"name": "Áo Polo Nam",
"price": 350000,
"stock": 45,
"category": "fashion"
}
Pros:
- ✅ Simple, easy to understand
- ✅ Cacheable (performance)
- ✅ Widely supported (every platform has REST API)
- ✅ Stateless (scalable)
Cons:
- ❌ Over-fetching (get entire product when you only need name)
- ❌ Under-fetching (need multiple requests for related data)
- ❌ Versioning complexity (API v1, v2, v3…)
When to use:
- Standard CRUD operations (Create, Read, Update, Delete)
- Public APIs (documentation easier)
- Simple integrations
GraphQL API (Modern, Flexible)
GraphQL = Query language for APIs (Facebook created)
Characteristics:
- Single endpoint (
/graphql) - Client specifies exactly what data needed
- Strongly typed schema
- Real-time subscriptions
Example Query:
query {
product(id: 123) {
name
price
}
}
Response:
{
"data": {
"product": {
"name": "Áo Polo Nam",
"price": 350000
}
}
}
Pros:
- ✅ Fetch exactly what you need (no over/under-fetching)
- ✅ Single request for multiple resources
- ✅ Strongly typed (self-documenting)
- ✅ Real-time with subscriptions
Cons:
- ❌ Learning curve (more complex than REST)
- ❌ Caching harder (not HTTP-based)
- ❌ Tooling less mature than REST
When to use:
- Complex data requirements (nested, related data)
- Mobile apps (minimize requests/bandwidth)
- Frontend-heavy apps (React, Vue)
Webhooks (Event-Driven)
Webhook = Reverse API (server calls YOU)
Concept:
- You provide URL endpoint
- External service POSTs data when event happens
- Real-time notifications
Example: Shopify order created → Shopify POSTs to your webhook URL:
POST https://yourdomain.com/webhooks/shopify-orders
Content-Type: application/json
{
"order_id": 12345,
"customer": "Nguyen Van A",
"total": 1500000,
"items": [...]
}
Your Server:
app.post('/webhooks/shopify-orders', (req, res) => {
const order = req.body;
// Process order (update CRM, accounting, warehouse)
processOrder(order);
// Respond 200 OK (acknowledge received)
res.status(200).send('OK');
});
Pros:
- ✅ Real-time (instant notifications)
- ✅ Efficient (no polling, only send when event happens)
- ✅ Push model (server-initiated)
Cons:
- ❌ Requires publicly accessible endpoint (hosting)
- ❌ Retry logic needed (if your server down)
- ❌ Security (verify webhook authenticity)
When to use:
- Real-time event notifications (orders, payments, updates)
- Avoid polling (checking for updates every X seconds)
2. Integration Patterns
Pattern 1: Point-to-Point Integration
Concept: Direct connection A ↔ B
Example:
Shopify → Custom script → Google Sheets
Code Example (Node.js):
const Shopify = require('shopify-api-node');
const { google } = require('googleapis');
// Shopify client
const shopify = new Shopify({
shopName: 'your-shop',
apiKey: 'YOUR_API_KEY',
password: 'YOUR_PASSWORD'
});
// Get orders from Shopify
const orders = await shopify.order.list({ limit: 50 });
// Write to Google Sheets
const sheets = google.sheets('v4');
orders.forEach(order => {
sheets.spreadsheets.values.append({
spreadsheetId: 'YOUR_SHEET_ID',
range: 'Orders!A:F',
valueInputOption: 'USER_ENTERED',
resource: {
values: [[
order.id,
order.customer.email,
order.total_price,
order.created_at
]]
}
});
});
Pros:
- ✅ Simple (2 systems only)
- ✅ Fast to implement
Cons:
- ❌ Doesn’t scale (N systems = N² integrations)
- ❌ Maintenance nightmare
When to use:
- Proof of concept
- <5 systems
Pattern 2: Hub-and-Spoke (iPaaS)
Concept: Central integration hub connects all systems
Example:
Zapier/Make (Hub)
/ | \
Shopify CRM Accounting
Tools:
- Zapier ($20-600/month) – No-code, 5,000+ apps
- Make (Integromat) ($10-300/month) – Visual, complex workflows
- n8n (free, self-hosted) – Open-source alternative
Workflow Example (Zapier):
Trigger: New Shopify Order
Actions:
1. Create customer in HubSpot CRM
2. Create invoice in Xero Accounting
3. Send notification to Slack
4. Add row to Google Sheets (reporting)
Pros:
- ✅ No-code (non-developers can build)
- ✅ Pre-built connectors (5,000+ apps)
- ✅ Scales better than point-to-point
Cons:
- ❌ Cost (per task/execution)
- ❌ Limited customization
- ❌ Vendor lock-in
When to use:
- Non-technical teams
- Standard integrations (common apps)
- Budget <50 triệu/năm
Pattern 3: Custom Integration Layer
Concept: Build your own integration service
Architecture:
┌─────────────────────────────────────┐
│ Custom Integration Service │
│ (Node.js / Laravel / Python) │
│ │
│ ┌─────────────────────────────┐ │
│ │ Message Queue (RabbitMQ) │ │
│ └─────────────────────────────┘ │
│ │
│ ┌─────────────────────────────┐ │
│ │ Database (MongoDB/SQL) │ │
│ └─────────────────────────────┘ │
└─────────────────────────────────────┘
↓ ↓ ↓
Shopify CRM Accounting
Tech Stack:
- Backend: Node.js (Express), Laravel (PHP), Python (Django)
- Queue: RabbitMQ, Redis, AWS SQS
- Database: MongoDB (flexible), PostgreSQL (relational)
- Cron: Schedule sync jobs
Example (Node.js + Express):
const express = require('express');
const app = express();
// Webhook receiver
app.post('/webhooks/shopify-order', async (req, res) => {
const order = req.body;
// Add to queue (process asynchronously)
await queue.add('process-order', { order });
// Respond immediately (don't block Shopify)
res.status(200).json({ received: true });
});
// Queue processor
queue.process('process-order', async (job) => {
const { order } = job.data;
// Sync to CRM
await hubspot.contacts.create({
email: order.customer.email,
properties: { ... }
});
// Create invoice in accounting
await xero.invoices.create({ ... });
// Update warehouse system
await warehouse.orders.create({ ... });
});
app.listen(3000);
Pros:
- ✅ Full control (custom logic)
- ✅ No per-task costs (only hosting)
- ✅ Complex workflows possible
- ✅ Scalable (horizontal scaling)
Cons:
- ❌ Development time (weeks-months)
- ❌ Maintenance (ongoing dev effort)
- ❌ Requires technical team
When to use:
- Complex business logic
- >10 systems integrated
- High volume (>10,000 transactions/day)
- Budget >100 triệu (development)
3. Authentication & Security
API Key (Simplest)
How it works:
- API provides you a key (long string)
- Include in every request (header or query param)
Example:
GET https://api.example.com/products
Authorization: Bearer sk_live_abc123xyz789
Pros:
- ✅ Simple to implement
- ✅ Easy to revoke (regenerate key)
Cons:
- ❌ If leaked, full access (no user-level permissions)
- ❌ Transmitted in every request (security risk if not HTTPS)
Best Practices:
- Always use HTTPS (not HTTP)
- Never commit keys to Git (use .env files)
- Rotate keys regularly (every 90 days)
OAuth 2.0 (User Authorization)
How it works:
- User logs in to service (e.g., Google)
- Service issues access token
- Your app uses token to access user’s data
Example Flow:
1. User clicks "Connect Google Drive"
2. Redirected to Google login
3. User approves permissions
4. Google redirects back with authorization code
5. Your backend exchanges code for access token
6. Use token to access Google Drive API
Pros:
- ✅ User-level permissions (scope-limited)
- ✅ Secure (user doesn’t share password with you)
- ✅ Revocable (user can disconnect anytime)
Cons:
- ❌ Complex implementation (OAuth flow)
- ❌ Token expiration (need refresh logic)
When to use:
- Third-party integrations (Google, Facebook, GitHub)
- User authorizes your app to access their data
Webhook Security
Problem: Anyone can POST to your webhook URL (spoofing attacks)
Solution: Verify signature
Example (Shopify):
const crypto = require('crypto');
app.post('/webhooks/shopify', (req, res) => {
// Get signature from header
const hmac = req.get('X-Shopify-Hmac-Sha256');
// Calculate expected signature
const hash = crypto
.createHmac('sha256', SHOPIFY_WEBHOOK_SECRET)
.update(req.rawBody)
.digest('base64');
// Verify
if (hash === hmac) {
// Legitimate request from Shopify
processWebhook(req.body);
res.status(200).send('OK');
} else {
// Spoofed request, reject
res.status(401).send('Unauthorized');
}
});
Best Practice:
- Always verify webhook signatures
- Use HTTPS (encrypt transit)
- Log suspicious requests
4. Error Handling & Monitoring
Retry Logic (Webhooks)
Problem: Your server down khi webhook arrives → data lost
Solution: Retry with exponential backoff
async function processWebhook(data, attempt = 1) {
try {
// Process data
await saveToDatabase(data);
await updateCRM(data);
return { success: true };
} catch (error) {
if (attempt < 5) {
// Retry with exponential backoff
const delay = Math.pow(2, attempt) * 1000; // 2s, 4s, 8s, 16s
console.log(`Retry attempt ${attempt} after ${delay}ms`);
await sleep(delay);
return processWebhook(data, attempt + 1);
} else {
// Failed after 5 attempts
console.error('Max retries exceeded', error);
await logToErrorTracking(error, data);
throw error;
}
}
}
Rate Limiting (API Calls)
Problem: API has rate limits (e.g., 1000 requests/hour)
Solution: Throttle requests
const Bottleneck = require('bottleneck');
// Max 100 requests/minute
const limiter = new Bottleneck({
minTime: 600, // 600ms between requests (100 req/min)
maxConcurrent: 5 // Max 5 concurrent
});
// Wrap API calls
const rateLimitedFetch = limiter.wrap(fetch);
// Use
orders.forEach(order => {
rateLimitedFetch(`https://api.example.com/orders/${order.id}`);
});
Monitoring & Alerting
Tools:
- Sentry – Error tracking ($26-80/tháng)
- New Relic – APM (application performance monitoring)
- Datadog – Infrastructure + logs
- PagerDuty – Alerting (on-call)
Metrics to Track:
- API response time (latency)
- Error rate (4xx, 5xx)
- Webhook success rate
- Queue length (backlog)
Alerting Rules:
IF error_rate > 5% FOR 5 minutes
THEN alert #engineering-channel
IF queue_length > 1000
THEN alert #engineering-channel
IF API_latency > 2 seconds
THEN alert #engineering-channel
5. Real-World Example: E-Commerce Integration
Scenario
Systems:
- E-commerce: Shopify
- CRM: HubSpot
- Accounting: Xero
- Shipping: GHTK (Vietnam)
Requirements:
- New order → Create customer in CRM
- New order → Create invoice in accounting
- Order paid → Trigger shipping
- Shipping completed → Update order status
- Real-time sync (webhooks)
Architecture
Shopify (Webhooks)
↓
Custom Integration Service (Node.js)
↓
Queue (RabbitMQ)
↓
Workers (Process jobs)
↓ ↓ ↓
HubSpot Xero GHTK
Implementation
Step 1: Webhook Receiver
app.post('/webhooks/shopify/orders', async (req, res) => {
const order = req.body;
// Verify Shopify signature
if (!verifyShopifyWebhook(req)) {
return res.status(401).send('Unauthorized');
}
// Add to queue
await queue.add('process-order', { order });
res.status(200).json({ received: true });
});
Step 2: Process Order (Queue Worker)
queue.process('process-order', async (job) => {
const { order } = job.data;
// 1. Create/update customer in HubSpot
const contact = await hubspot.contacts.createOrUpdate({
email: order.customer.email,
properties: {
firstname: order.customer.first_name,
lastname: order.customer.last_name,
phone: order.customer.phone,
total_revenue: order.total_price
}
});
// 2. Create invoice in Xero
const invoice = await xero.invoices.create({
type: 'ACCREC', // Accounts Receivable
contact: {
name: order.customer.name,
emailAddress: order.customer.email
},
lineItems: order.line_items.map(item => ({
description: item.name,
quantity: item.quantity,
unitAmount: item.price,
taxType: 'OUTPUT', // VAT
accountCode: '200' // Sales
})),
dueDate: moment().add(7, 'days').format('YYYY-MM-DD'),
reference: `Shopify Order ${order.id}`
});
// 3. If order paid, create shipping order
if (order.financial_status === 'paid') {
const shipping = await ghtk.orders.create({
pick_name: 'Your Store',
pick_address: 'Store address...',
pick_province: 'TP. Hồ Chí Minh',
pick_tel: '0901234567',
name: order.shipping_address.name,
address: order.shipping_address.address1,
province: order.shipping_address.province,
tel: order.shipping_address.phone,
products: order.line_items.map(item => ({
name: item.name,
weight: item.grams,
quantity: item.quantity,
price: item.price
})),
order_payment_method: order.payment_method === 'COD' ? 1 : 2
});
// Update Shopify order with tracking
await shopify.order.update(order.id, {
fulfillment: {
tracking_number: shipping.label_id,
tracking_company: 'GHTK'
}
});
}
console.log(`Order ${order.id} processed successfully`);
});
Results
Before Integration:
- Nhân viên manually:
- Copy customer từ Shopify → HubSpot (5 phút/order)
- Create invoice trong Xero (10 phút/order)
- Create shipping order GHTK (5 phút/order)
- Total: 20 phút/order
- 100 orders/ngày = 33 giờ/ngày (4 nhân viên!)
After Integration:
- Automatic: 0 phút manual work
- Real-time: Data synced instantly
- Accuracy: 100% (no human errors)
Cost:
- Development: 80 triệu (one-time)
- Hosting: 3 triệu/tháng (server)
- Savings: 4 nhân viên × 15 triệu = 60 triệu/tháng
- ROI: Pay back in 2 tháng!
Kết Luận
API integration = Game changer cho business efficiency.
Key Takeaways:
- ✅ REST API: Standard, widely supported
- ✅ GraphQL: Flexible, efficient (modern apps)
- ✅ Webhooks: Real-time events
- ✅ iPaaS (Zapier): Fast, no-code (<10 systems)
- ✅ Custom: Full control (>10 systems, complex logic)
Security:
- HTTPS always
- Verify webhook signatures
- Never commit API keys to Git
Monitoring:
- Track error rates, latency
- Alert on failures
- Retry logic with backoff
Investment:
- No-code (Zapier): $20-600/tháng
- Custom: 50-200 triệu dev, 5-20 triệu/tháng maintenance
- ROI: 2-6 tháng payback (typical)
Bai Viet Lien Quan
Creps.vn – API Integration Experts
Creps.vn specializes in system integrations & automation workflows.
Services:
Package 1: Simple Integration (10-20 triệu)
- 2-3 systems (e.g., Shopify + CRM + Accounting)
- Zapier/Make setup (no-code)
- Documentation & training
Package 2: Custom Integration (50-100 triệu)
- 5-10 systems
- Custom Node.js/Laravel integration layer
- Webhooks, queues, error handling
- Monitoring & alerts
- 3 tháng support
Package 3: Enterprise (150+ triệu)
- Unlimited systems
- Microservices architecture
- Real-time sync
- High availability (99.9% uptime)
- Dedicated support
Portfolio:
🔗 Integration Projects:
- E-commerce (Shopify) + CRM + Accounting + Shipping
- Booking platform + Payment gateways + Calendar
- Warehouse management + ERP + Logistics
- 30+ integrations built, 10 triệu transactions processed
Contact:
📞 Hotline: 093.102.1874 📧 Email: [email protected] 🌐 Website: https://creps.vn/api-integration
Free Consultation:
- ✅ System audit (what needs integration?)
- ✅ Architecture recommendations
- ✅ Cost estimate (Zapier vs custom)
- ✅ ROI calculation
Tags: #APIIntegration #SystemIntegration #Automation #Webhooks #REST #GraphQL #CrepsVietnam
Bài liên quan:
📚 Bài Viết Liên Quan
👉 AI Automation Workflow
AI + API integration
👉 Chatbot API Integration
Kết nối chatbot CRM
👉 WordPress API
WordPress external APIs
