MinAI - Về trang chủ
Hướng dẫn
8/1340 phút
Đang tải...

HTTP Requests & APIs

Kết nối với bất kỳ API nào thông qua HTTP Request node

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.

0

🎯 Mục tiêu bài học

TB5 min

🎯 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?

1

🌐 HTTP Basics

TB5 min

1. HTTP Basics

1.1 HTTP Methods

MethodPurposeExample
GETLấy dataGet list of users
POSTTạo mớiCreate new user
PUTCập nhật toàn bộReplace user data
PATCHCập nhật một phầnUpdate user email
DELETEXóaDelete user

1.2 Request Structure

🌐HTTP Message
📤Request
🔧Method: GET / POST / PUT / DELETE
🔗URL: https://api.example.com/users
📋Headers
📄Content-Type: application/json
🔑Authorization: Bearer token123
🔍Query Parameters: ?page=1&limit=10
📦Body (POST/PUT): {name, email}
📥Response
🔢Status Code: 200, 201, 404, 500...
📋Headers: Content-Type, etc.
📦Body: {data: [...]}

1.3 Status Codes

Ví dụ
12xx Success:
2 200 OK — Request thành công
3 201 Created — Tạo mới thành công
4 204 No Content — Thành công, không có data
5
64xx Client Error:
7 400 Bad Request — Request sai format
8 401 Unauthorized — Chưa đăng nhập
9 403 Forbidden — Không có quyền
10 404 Not Found — Không tìm thấy
11
125xx Server Error:
13 500 Internal Server Error — Lỗi server
14 503 Service Unavailable — Server quá tải

Checkpoint

Phân biệt HTTP GET và POST. Status code 200, 401, 404 có ý nghĩa gì?

2

🔧 HTTP Request Node

TB5 min

2. HTTP Request Node

2.1 Basic GET Request

Ví dụ
1HTTP Request node:
2- Method: GET
3- URL: https://api.publicapis.org/entries
4- Response: JSON (auto-parsed)

2.2 GET with Parameters

Ví dụ
1HTTP Request node:
2- Method: GET
3- URL: https://api.openweathermap.org/data/2.5/weather
4- Query Parameters:
5 - q: Hanoi
6 - appid: YOUR_API_KEY
7 - units: metric
8 - lang: vi

Equivalent URL: https://api.openweathermap.org/data/2.5/weather?q=Hanoi&appid=KEY&units=metric&lang=vi

2.3 POST Request

Ví dụ
1HTTP Request node:
2- Method: POST
3- URL: https://api.example.com/users
4- Headers:
5 - Content-Type: application/json
6- Body (JSON):
7 {
8 "name": "{{ $json.name }}",
9 "email": "{{ $json.email }}",
10 "role": "member"
11 }

2.4 Dynamic URLs

Ví dụ
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ụ.

3

🔐 Authentication

TB5 min

3. Authentication

3.1 API Key (trong header)

Ví dụ
1HTTP Request node:
2- Authentication: Generic
3- Headers:
4 - X-API-Key: your-api-key-here

3.2 Bearer Token

Ví dụ
1HTTP Request node:
2- Authentication: Generic
3- Headers:
4 - Authorization: Bearer your-token-here

3.3 Basic Auth

Ví dụ
1HTTP Request node:
2- Authentication: Basic Auth
3- Username: your-username
4- Password: your-password

3.4 OAuth2

Ví dụ
1HTTP Request node:
2- Authentication: OAuth2
3- Grant Type: Authorization Code
4- Auth URL: https://provider.com/oauth/authorize
5- Token URL: https://provider.com/oauth/token
6- Client ID: xxx
7- Client Secret: yyy
8- Scope: read write

3.5 Credentials Best Practice

Ví dụ
1⚠️ NEVER hardcode API keys in workflow!
2
3✅ Use n8n Credentials:
41. Settings → Credentials → Add
52. Select type (Header Auth, OAuth2, etc.)
63. Enter secrets once
74. Reference in nodes
8
9Benefits:
10- Encrypted storage
11- Share across workflows
12- Update once, apply everywhere

Checkpoint

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?

4

📡 Working with APIs

TB5 min

4. Working with APIs

4.1 Pagination

Many APIs return data in pages. Handle pagination:

Ví dụ
1Loop pattern:
21. GET page 1 → save results
32. Check if more pages (next_page_url or total > offset)
43. GET page 2 → append results
54. Repeat until done
Ví dụ
1HTTP Request node:
2- URL: https://api.example.com/items?page={{ $json.currentPage }}&limit=100
3
4→ IF (hasNextPage)
5 → Increment page
6 → Loop back to HTTP Request
7→ ELSE
8 → Continue with all data

4.2 Rate Limiting

Ví dụ
1Problem: API cho phép 60 requests/minute
2Solution: Add Wait node giữa requests
3
4HTTP Request → Wait (1 second) → Next request
5
6Or use n8n's built-in:
7HTTP Request node → Settings → Retry on Fail → Retry interval

4.3 Error Handling

Ví dụ
1HTTP Request node settings:
2- Continue on Fail: ON
3- Check: {{ $json.statusCode }}
4 → IF 200: Process data
5 → IF 429: Wait & retry (rate limited)
6 → IF 401: Refresh token
7 → IF 500: Log error & alert

4.4 Response Parsing

Ví dụ
1API Response (JSON):
2{
3 "data": {
4 "users": [
5 {"id": 1, "name": "Alice"},
6 {"id": 2, "name": "Bob"}
7 ],
8 "total": 150,
9 "page": 1
10 }
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?

5

🔥 Real API Examples

TB5 min

5. Real API Examples

5.1 OpenAI API

Ví dụ
1HTTP Request:
2- Method: POST
3- URL: https://api.openai.com/v1/chat/completions
4- Headers:
5 - Authorization: Bearer sk-xxxxx
6 - Content-Type: application/json
7- 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.7
15}

5.2 Telegram Bot API

Ví dụ
1HTTP Request:
2- Method: POST
3- URL: https://api.telegram.org/bot{TOKEN}/sendMessage
4- Body:
5{
6 "chat_id": "{{ $json.chatId }}",
7 "text": "{{ $json.message }}",
8 "parse_mode": "Markdown"
9}

5.3 GitHub API

Ví dụ
1HTTP Request:
2- Method: GET
3- URL: https://api.github.com/repos/{owner}/{repo}/issues
4- Headers:
5 - Authorization: token ghp_xxxxx
6 - Accept: application/vnd.github.v3+json
7- Query: state=open&labels=bug

5.4 VNPay / Momo (Vietnam Payment)

Ví dụ
1HTTP Request:
2- Method: POST
3- URL: https://sandbox.vnpayment.vn/paymentv2/vpcpay.html
4- 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ì?

6

🚀 Advanced Patterns

TB5 min

6. Advanced Patterns

6.1 API Chaining

Ví dụ
1Step 1: HTTP GET /users/123 → Get user data
2Step 2: HTTP GET /orders?userId=123 → Get user's orders
3Step 3: HTTP GET /products/{{ orderId }} → Get product details

6.2 Parallel Requests

Ví dụ
1Split In Batches node → HTTP Request (parallel)
2→ Merge results
3
4Or: Use n8n's built-in batch settings
5HTTP Request → Settings → Batch Size: 5

6.3 Webhook → API → Response

Ví dụ
1Webhook (receive request)
2→ HTTP Request (call external API)
3→ Transform data
4→ Respond to Webhook (return result)
5
6This makes n8n a middleware/proxy!

7. Hands-on Lab

Lab 1: Weather Dashboard

  1. Schedule (every 3 hours)
  2. HTTP Request — OpenWeatherMap API for 5 cities
  3. Loop — Format each city's weather
  4. Google Sheets — Log data
  5. Slack — Post summary if extreme weather

Lab 2: API Aggregator

Build workflow that aggregates data from 3 APIs:

  1. HTTP — Get news headlines (NewsAPI)
  2. HTTP — Get stock prices (Alpha Vantage)
  3. HTTP — Get weather
  4. Merge — Combine all data
  5. Slack — Post morning briefing

Lab 3: REST API Proxy

Build n8n as middleware:

  1. Webhook (receive request)
  2. Validate request data
  3. HTTP Request (call backend API)
  4. Transform response
  5. Respond with formatted data

📝 Quiz

  1. 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
  2. Status code 429 nghĩa là?

    • Not Found
    • Server Error
    • Too Many Requests (rate limited)
    • Unauthorized
  3. API key nên lưu ở đâu trong n8n?

    • Hardcode trong URL
    • Clipboard
    • n8n Credentials (encrypted)
    • Text file trên desktop

🎯 Key Takeaways

  1. HTTP Request node — Kết nối với mọi API
  2. Methods — GET (read), POST (create), PUT (update), DELETE (remove)
  3. Authentication — API key, Bearer token, OAuth2 (use Credentials!)
  4. Error handling — Continue on fail + status code checks
  5. 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!