在現代 Web 開發中,API 已成為連接前后端的核心橋梁,傳統的做法是通過后端框架來構建API接口,然后由前后端人員進行聯調。
PostgREST是基于無服務器的一種實現方案,允許開發者將PostgreSQL數據庫直接暴露為RESTful API,而無需編寫任何后端代碼,從而可以專注于核心功能的開發。
基本介紹
PostgREST可以理解為自帶JWT解析的postgres后端API,最主要提供了兩方面的功能:
- PostgREST 可以自動將 PostgreSQL 的表、視圖、函數等映射為 RESTful 接口,無需手動編寫任何 CRUD 代碼,在簡單的數據庫使用場景下可省略后端;
- 內置身份驗證,自動將請求頭的token解析出來,用于角色權限管理
簡單測試
安裝
前提:安裝了PostgreSQL數據庫
# Macos
brew install postgrest# Arch Linux
pacman -S postgrest# Docker
docker pull postgrest/postgrest
數據庫設置
首先登陸數據庫,接著創建一個視圖:
create schema api;
創建一張測試表:
create table api.todos (id int primary key generated by default as identity,done boolean not null default false,task text not null,due timestamptz
);insert into api.todos (task) values('finish tutorial 0'), ('pat self on back');
創建匿名角色,并且賦予查詢api.todos
的權限:
create role web_anon nologin;grant usage on schema api to web_anon;
grant select on api.todos to web_anon;
創建用于登陸數據庫的角色:
create role authenticator noinherit login password 'mysecretpassword';
grant web_anon to authenticator;
創建配置文件
db-uri = "postgres://authenticator:mysecretpassword@localhost:5432/postgres"
db-schemas = "api"
db-anon-role = "web_anon"
web_anon這個角色是之前在數據庫中就已經配置好的
啟動服務
postgrest tutorial.conf
測試響應
直接用curl
發起請求:
curl http://localhost:3000/todos
返回:
[{"id": 1,"done": false,"task": "finish tutorial 0","due": null},{"id": 2,"done": false,"task": "pat self on back","due": null}
]
基本操作
查詢
直接在端口后面跟上需要查詢的表名,即可對該表進行查詢
curl "http://localhost:3000/people?age=gte.18&student=is.true"
同樣支持過濾條件,在PostgREST中需要以簡寫方式聲明。
部分簡寫如下:
Abbreviation | In PostgreSQL | Meaning |
---|---|---|
eq | = | equals |
gt | > | greater than |
gte | >= | greater than or equal |
lt | < | less than |
lte | <= | less than or equal |
neq | <> or != | not equal |
新增
插入單條數據:
curl "http://localhost:3000/table_name" \-X POST -H "Content-Type: application/json" \-d '{ "col1": "value1", "col2": "value2" }'
披量插入數據:
curl "http://localhost:3000/people" \-X POST -H "Content-Type: application/json" \-d @- << EOF[{ "name": "J Doe", "age": 62, "height": 70 },{ "name": "Janus", "age": 10, "height": 55 }]
EOF
更新
使用PATCH
更新數據:
curl "http://localhost:3000/people?age=lt.13" \-X PATCH -H "Content-Type: application/json" \-d '{ "category": "child" }'
刪除
使用DELETE
刪除數據:
curl "http://localhost:3000/user?active=is.false" -X DELETE
總結
PostgREST 提供了一種高效、簡潔的方式來構建 RESTful API,特別適合那些希望減少后端開發負擔、專注于核心功能開發的團隊。