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.运行 PostgRES

(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



猜你喜欢

转载自www.cnblogs.com/hanvans/p/12368181.html