HTTP Requests & APIs
HTTP Request node là "Swiss army knife" của n8n — kết nối với BẤT KỲ API nào, kể cả khi n8n chưa có native node.
🎯 Mục tiêu bài học
🎯 Mục tiêu
- Hiểu HTTP methods (GET, POST, PUT, DELETE)
- Sử dụng HTTP Request node
- Authentication (API key, Bearer, OAuth)
- Parse và xử lý API responses
Checkpoint
HTTP Request node trong n8n được ví như gì? Tại sao nó quan trọng?
🌐 HTTP Basics
1. HTTP Basics
1.1 HTTP Methods
| Method | Purpose | Example |
|---|---|---|
| GET | Lấy data | Get list of users |
| POST | Tạo mới | Create new user |
| PUT | Cập nhật toàn bộ | Replace user data |
| PATCH | Cập nhật một phần | Update user email |
| DELETE | Xóa | Delete user |
1.2 Request Structure
1.3 Status Codes
12xx Success:2 200 OK — Request thành công3 201 Created — Tạo mới thành công4 204 No Content — Thành công, không có data5 64xx Client Error:7 400 Bad Request — Request sai format8 401 Unauthorized — Chưa đăng nhập9 403 Forbidden — Không có quyền10 404 Not Found — Không tìm thấy11 125xx Server Error:13 500 Internal Server Error — Lỗi server14 503 Service Unavailable — Server quá tảiCheckpoint
Phân biệt HTTP GET và POST. Status code 200, 401, 404 có ý nghĩa gì?
🔧 HTTP Request Node
2. HTTP Request Node
2.1 Basic GET Request
1HTTP Request node:2- Method: GET3- URL: https://api.publicapis.org/entries4- Response: JSON (auto-parsed)2.2 GET with Parameters
1HTTP Request node:2- Method: GET3- URL: https://api.openweathermap.org/data/2.5/weather4- Query Parameters:5 - q: Hanoi6 - appid: YOUR_API_KEY7 - units: metric8 - lang: viEquivalent URL: https://api.openweathermap.org/data/2.5/weather?q=Hanoi&appid=KEY&units=metric&lang=vi
2.3 POST Request
1HTTP Request node:2- Method: POST3- URL: https://api.example.com/users4- Headers:5 - Content-Type: application/json6- Body (JSON):7 {8 "name": "{{ $json.name }}",9 "email": "{{ $json.email }}",10 "role": "member"11 }2.4 Dynamic URLs
1URL: https://api.example.com/users/{{ $json.userId }}2 3Sử dụng expressions để build URL từ previous node data.Checkpoint
Cách cấu hình HTTP Request node cho POST request gồm những gì? Cho ví dụ.
🔐 Authentication
3. Authentication
3.1 API Key (trong header)
1HTTP Request node:2- Authentication: Generic3- Headers:4 - X-API-Key: your-api-key-here3.2 Bearer Token
1HTTP Request node:2- Authentication: Generic3- Headers:4 - Authorization: Bearer your-token-here3.3 Basic Auth
1HTTP Request node:2- Authentication: Basic Auth3- Username: your-username4- Password: your-password3.4 OAuth2
1HTTP Request node:2- Authentication: OAuth23- Grant Type: Authorization Code4- Auth URL: https://provider.com/oauth/authorize5- Token URL: https://provider.com/oauth/token6- Client ID: xxx7- Client Secret: yyy8- Scope: read write3.5 Credentials Best Practice
1⚠️ NEVER hardcode API keys in workflow!2 3✅ Use n8n Credentials:41. Settings → Credentials → Add52. Select type (Header Auth, OAuth2, etc.)63. Enter secrets once74. Reference in nodes8 9Benefits:10- Encrypted storage11- Share across workflows12- Update once, apply everywhereCheckpoint
Tại sao KHÔNG nên hardcode API key trong workflow? n8n Credentials giải quyết vấn đề này như thế nào?
📡 Working with APIs
4. Working with APIs
4.1 Pagination
Many APIs return data in pages. Handle pagination:
1Loop pattern:21. GET page 1 → save results32. Check if more pages (next_page_url or total > offset)43. GET page 2 → append results54. Repeat until done1HTTP Request node:2- URL: https://api.example.com/items?page={{ $json.currentPage }}&limit=1003 4→ IF (hasNextPage)5 → Increment page6 → Loop back to HTTP Request7→ ELSE8 → Continue with all data4.2 Rate Limiting
1Problem: API cho phép 60 requests/minute2Solution: Add Wait node giữa requests3 4HTTP Request → Wait (1 second) → Next request5 6Or use n8n's built-in:7HTTP Request node → Settings → Retry on Fail → Retry interval4.3 Error Handling
1HTTP Request node settings:2- Continue on Fail: ON3- Check: {{ $json.statusCode }}4 → IF 200: Process data5 → IF 429: Wait & retry (rate limited)6 → IF 401: Refresh token7 → IF 500: Log error & alert4.4 Response Parsing
1API Response (JSON):2{3 "data": {4 "users": [5 {"id": 1, "name": "Alice"},6 {"id": 2, "name": "Bob"}7 ],8 "total": 150,9 "page": 110 }11}12 13Access in n8n expressions:14- Total users: {{ $json.data.total }}15- First user name: {{ $json.data.users[0].name }}16- All users array: {{ $json.data.users }}Checkpoint
Pagination là gì? Khi API trả về nhiều trang dữ liệu, xử lý trong n8n bằng cách nào?
🔥 Real API Examples
5. Real API Examples
5.1 OpenAI API
1HTTP Request:2- Method: POST3- URL: https://api.openai.com/v1/chat/completions4- Headers:5 - Authorization: Bearer sk-xxxxx6 - Content-Type: application/json7- Body:8{9 "model": "gpt-4o-mini",10 "messages": [11 {"role": "system", "content": "Bạn là AI assistant."},12 {"role": "user", "content": "{{ $json.question }}"}13 ],14 "temperature": 0.715}5.2 Telegram Bot API
1HTTP Request:2- Method: POST3- URL: https://api.telegram.org/bot{TOKEN}/sendMessage4- Body:5{6 "chat_id": "{{ $json.chatId }}",7 "text": "{{ $json.message }}",8 "parse_mode": "Markdown"9}5.3 GitHub API
1HTTP Request:2- Method: GET3- URL: https://api.github.com/repos/{owner}/{repo}/issues4- Headers:5 - Authorization: token ghp_xxxxx6 - Accept: application/vnd.github.v3+json7- Query: state=open&labels=bug5.4 VNPay / Momo (Vietnam Payment)
1HTTP Request:2- Method: POST3- URL: https://sandbox.vnpayment.vn/paymentv2/vpcpay.html4- Body: (form parameters with hash signature)5 6⚠️ Payment APIs cần HMAC signing — sử dụng Code node để generate signature.Checkpoint
Cho ví dụ cách gọi OpenAI API từ n8n. Cần truyền những parameters gì?
🚀 Advanced Patterns
6. Advanced Patterns
6.1 API Chaining
1Step 1: HTTP GET /users/123 → Get user data2Step 2: HTTP GET /orders?userId=123 → Get user's orders3Step 3: HTTP GET /products/{{ orderId }} → Get product details6.2 Parallel Requests
1Split In Batches node → HTTP Request (parallel)2→ Merge results3 4Or: Use n8n's built-in batch settings5HTTP Request → Settings → Batch Size: 56.3 Webhook → API → Response
1Webhook (receive request)2→ HTTP Request (call external API)3→ Transform data4→ Respond to Webhook (return result)5 6This makes n8n a middleware/proxy!7. Hands-on Lab
Lab 1: Weather Dashboard
- Schedule (every 3 hours)
- HTTP Request — OpenWeatherMap API for 5 cities
- Loop — Format each city's weather
- Google Sheets — Log data
- Slack — Post summary if extreme weather
Lab 2: API Aggregator
Build workflow that aggregates data from 3 APIs:
- HTTP — Get news headlines (NewsAPI)
- HTTP — Get stock prices (Alpha Vantage)
- HTTP — Get weather
- Merge — Combine all data
- Slack — Post morning briefing
Lab 3: REST API Proxy
Build n8n as middleware:
- Webhook (receive request)
- Validate request data
- HTTP Request (call backend API)
- Transform response
- Respond with formatted data
📝 Quiz
-
HTTP GET khác POST ở điểm nào?
- GET lấy data, POST gửi data để tạo mới
- GET nhanh hơn
- POST miễn phí
- Không khác nhau
-
Status code 429 nghĩa là?
- Not Found
- Server Error
- Too Many Requests (rate limited)
- Unauthorized
-
API key nên lưu ở đâu trong n8n?
- Hardcode trong URL
- Clipboard
- n8n Credentials (encrypted)
- Text file trên desktop
🎯 Key Takeaways
- HTTP Request node — Kết nối với mọi API
- Methods — GET (read), POST (create), PUT (update), DELETE (remove)
- Authentication — API key, Bearer token, OAuth2 (use Credentials!)
- Error handling — Continue on fail + status code checks
- Pagination — Loop qua pages cho large datasets
Checkpoint
Webhook → API → Response pattern biến n8n thành gì? Cho ví dụ use case.
🚀 Bài tiếp theo
Expressions & Variables — Master n8n expressions để transform data!
