📌 คืออะไร?
Google Custom Search API (CSE API) เป็น API ที่ให้คุณ ค้นหาข้อมูลจาก Google ผ่านคำสั่งโปรแกรม (เช่น JavaScript, Node.js, PHP ฯลฯ)
✅ ขั้นตอนการใช้งานแบบฟรี (ฟรี 100 ครั้ง/วัน)
🔹 1. สร้าง API Key
- ไปที่: https://console.cloud.google.com/
- สร้าง Project ใหม่ หรือใช้ Project ที่มีอยู่
- ไปที่เมนู APIs & Services → Credentials
- คลิก Create Credentials → API Key
- Copy API Key ที่ได้ เช่น:
AIzaSy...XYZ
🔹 2. สร้าง Programmable Search Engine (PSE)
- ไปที่: https://programmablesearchengine.google.com/
- กด “Get Started”, ล็อกอินด้วย Google
- สร้างเครื่องมือค้นหาใหม่ (ใส่ *.com เพื่อค้นหาทั้งเว็บ)
- กด “Create” → ไปที่ “Control Panel”
- เปิด “Search the entire web” เพื่อให้ค้นหาจากทุกเว็บได้
- Copy Search Engine ID (cx) เช่น:
13e126c502be44f21
🔹 3. ทดลองเรียก API
https://www.googleapis.com/customsearch/v1?key=YOUR_API_KEY&cx=YOUR_CX_ID&q=ราคาทองวันนี้
🔹 4. ตัวอย่างโค้ดใน Node.js
const fetch = require("node-fetch");
const apiKey = "YOUR_API_KEY";
const cx = "YOUR_CX_ID";
const query = "ChatGPT คืออะไร";
const url = `https://www.googleapis.com/customsearch/v1?key=${apiKey}&cx=${cx}&q=${encodeURIComponent(query)}`;
fetch(url)
.then(res => res.json())
.then(data => {
console.log("ผลลัพธ์:");
data.items.forEach(item => {
console.log(`- ${item.title}`);
console.log(item.link);
console.log("------");
});
})
.catch(err => console.error(err));
🔢 จำกัดการใช้งาน (Free Tier Limits)
| รายการ | รายละเอียด |
|---|---|
| ✅ ฟรี | 100 queries ต่อวัน (ไม่ต้องผูกบัตรเครดิต) |
| 🚫 เกิน 100 | ต้องเปิด Billing และเสียเงิน: $5 ต่อ 1,000 queries |
| 🔁 สูงสุด | ใช้ได้สูงสุด 10,000 queries/วัน (แม้เปิด billing แล้ว) |
| ⚠️ ถ้าไม่เปิด billing | ระบบจะจำกัดไว้ที่ 100 queries/day แบบถาวร |
| 🔐 API Key ควรจำกัด | แนะนำให้ตั้งค่า Referrer หรือ IP whitelist ป้องกันการโดนขโมย |
![]()