PostgREST 是一個獨立的 Web 服務器,為 PostgreSQL 數據庫生成 RESTful API。 它提供基於底層數據庫結構定制的 API。
1.安裝 PostgreSQL
(1)啟動pg
(2)Docker 會暴露一個 5432 端來供你訪問 PostgreSQL server
sudo docker run --name tutorial -p 5432:5432 \ -e POSTGRES_PASSWORD=mysecretpassword \ -d postgres
2.安裝 PostgREST
(1)MACOS 下載 https://github.com/PostgREST/postgrest/releases/tag/v6.0.2 (postgrest-v6.0.2-osx.tar.xz) 解壓執行。
(2)執行 ./postgrest
3. 為 API 創建數據
(1)連上容器內的 SQL 控制台 (psql)
執行:sudo docker exec -it tutorial psql -U postgres。
(2)暴露在 API 中的數據庫對象創建一個 命名的 schema
create schema api;
(3)我們的 API 准備通過表來設置一個端點 /todos
。
create table api.todos ( |
接下來,創建一個角色來用於進行匿名的 web 請求。當一個請求進來,PostgREST 會在數據庫中切換到該角色進行查詢。
create role web_anon nologin; |
web_anon
角色擁有訪問 api
schema 的權限,可以讀取 todos
表中的數據(rows)。
4.運行 PostgREST
(1)PostgREST 使用一個配置文件來確定如何連接數據庫。創建一個文件 tutorial.conf
並加上如下內容:
db-uri = "postgres://postgres:mysecretpassword@localhost/postgres" |
(2)在目錄postgrest下執行
./postgrest tutorial.conf
(3)web服務啟動起來
Listening on port 3000 Attempting to connect to the database... Connection successful
打開一個新的 terminal (保持 PostgREST 依舊運行)。嘗試對 todos 做一個 HTTP 請求。
|