PostgreSQL神器之PostgREST(macos版本使用)


 

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 (
id serial primary key,
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');

接下來,創建一個角色來用於進行匿名的 web 請求。當一個請求進來,PostgREST 會在數據庫中切換到該角色進行查詢。

 

create role web_anon nologin;
grant web_anon to postgres;

grant usage on schema api to web_anon;
grant select on api.todos to web_anon;

web_anon 角色擁有訪問 api schema 的權限,可以讀取 todos 表中的數據(rows)。

 

4.運行 PostgREST

(1)PostgREST 使用一個配置文件來確定如何連接數據庫。創建一個文件 tutorial.conf 並加上如下內容:

db-uri = "postgres://postgres:mysecretpassword@localhost/postgres"
db-schema = "api"
db-anon-role = "web_anon"

(2)在目錄postgrest下執行

 

      ./postgrest tutorial.conf

 

(3)web服務啟動起來  

Listening on port 3000
Attempting to connect to the database...
Connection successful

打開一個新的 terminal (保持 PostgREST 依舊運行)。嘗試對 todos 做一個 HTTP 請求。

curl http://localhost:3000/todos




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM