到目前為止,我們已經熟悉了 Odoo 的 Model 與 View,這些功能主要用於內部系統的資料管理。但若企業需要與外部系統(例如電商平台、行動應用、IoT 裝置)交換資料,就需要用到 Controllers 與 REST API。今天我們將介紹 Odoo 中的 Controller 概念,並透過範例建立一個簡單的 API。
在 Odoo 中,Controller 負責處理 HTTP 請求,扮演「使用者/外部系統 ↔ Odoo 內部模型」的橋樑。
@http.route
裝飾器設定。先在模組中新增一個資料夾 controllers/
,並建立檔案 controllers/hello_controller.py
。
範例:
from odoo import http
class HelloController(http.Controller):
@http.route('/hello', type='http', auth='public')
def hello(self, **kwargs):
return "Hello from Odoo Controller!"
啟動 Odoo 後,訪問 http://localhost:8069/hello,即可看到文字輸出。
若要讓外部系統存取 Odoo 資料,可以透過 JSON 格式回傳。
範例:建立一個查詢書籍清單的 API。
from odoo import http
class LibraryAPI(http.Controller):
@http.route('/api/books', type='json', auth='public', methods=['GET'])
def list_books(self, **kwargs):
books = http.request.env['library.book'].search([])
return [{'id': b.id, 'title': b.name, 'author': b.author} for b in books]
啟動後,訪問:
curl -X GET http://localhost:8069/api/books
回傳結果會是:
[
{"id": 1, "title": "Odoo Basics", "author": "Tom"},
{"id": 2, "title": "Advanced Odoo", "author": "Alice"}
]
在實務上,建議搭配 API Key 或 OAuth2 進行授權,確保資料不會被未授權的外部系統濫用。
Odoo Controllers 讓系統不再是「封閉式 ERP」,而是能與外部世界互動的平台。
@http.route
定義路由。在下一篇文章中,我將示範如何 擴充 CRM 模組功能,帶你從官方模組下手,體驗真正的二次開發。