PostgREST用于直接产生restapi接口来进行CRUD操作,降低了后端开发工作量,提供高度一致规范的数据的接口,在某些场景下具有很重要的应用价值。
环境说明
OS版本:CentOS Linux release 7.7.1908
PostgreSQL版本:PostgreSQL 10,安装过程可以参考另一篇Blog。
注意PostgREST依赖PostgreSQL 9.5以上
进入psql命令行,创建一个devuser,为这个用户创建一个数据库devdb。
psql -U postgres
postgres=# CREATE USER devuser WITH PASSWORD '******';
CREATE ROLE
postgres=# CREATE DATABASE devdb OWNER devuser ENCODING = 'UTF8';
使用devuser登录,创建一张测试表,插入几行记录,并查看
psql -U devuser --password devdb
devdb=> create table rest_data(id int,rest_content varchar(12));
devdb=> insert into rest_data values(1,'Hello');
devdb=> insert into rest_data values(2,'world');
devdb=> insert into rest_data values(3,'This');
devdb=> insert into rest_data values(4,'is');
devdb=> insert into rest_data values(5,'a');
devdb=> insert into rest_data values(6,'restapi');
devdb=> select * from rest_data ;
devdb=> \q
由于PostgREST是用Haskell编写的,如果直接编译,还需要准备Haskell环境,这里我直接采用编译好的release版本,参考release版本的地址。
wget https://github.com/PostgREST/postgrest/releases/download/v6.0.2/postgrest-v6.0.2-centos7.tar.xz
tar -xvf postgrest-v6.0.2-centos7.tar.xz
解压该文件可以看到只有一个postgrest程序文件,我们直接执行该文件,报出提示:
Missing: FILENAME
Usage: postgrest FILENAME
PostgREST 6.0.2 (713b214) / create a REST API to an existing Postgres database
Available options:
-h,--help Show this help text
FILENAME Path to configuration file
Example Config File:
db-uri = "postgres://user:pass@localhost:5432/dbname"
db-schema = "public" # this schema gets added to the search_path of every request
db-anon-role = "postgres"
db-pool = 10
db-pool-timeout = 10
server-host = "!4"
server-port = 3000
...
说明该执行文件执行的时候需要跟一个配置文件参数。
为了严格区分,我将PostgREST相关文件/usr/local/pgrest目录下,在这个目录分别建立bin、cfg、log文件夹,用来分别存储执行文件,配置文件和日志文件。
mkdir -p /usr/local/pgrest/bin
mkdir -p /usr/local/pgrest/cfg
mkdir -p /usr/local/pgrest/log
将执行文件移动到/usr/local/pgrest/bin目录下
mv postgrest /usr/local/pgrest/bin/
编写配置文件/usr/local/pgrest/cfg/default.conf
vi /usr/local/pgrest/cfg/default.conf
# 配置文件
db-uri = "postgres://devuser:****@192.168.56.120:5432/devdb"
db-schema = "public" # this schema gets added to the search_path of every request
db-anon-role = "devuser"
db-pool = 10
db-pool-timeout = 10
server-host = "!4"
server-port = 3000
注意:
运行测试
/usr/local/pgrest/bin/postgrest /usr/local/pgrest/cfg/default.conf
Attempting to connect to the database...
Listening on port 3000
Connection successful
再开一个窗口用curl访问一下接口试试:
curl -X GET "http://192.168.56.120:3000/rest_data?limit=10"
返回结果:
[{"id":1,"rest_content":"Hello"},
{"id":2,"rest_content":"world"},
{"id":3,"rest_content":"This"},
{"id":4,"rest_content":"is"},
{"id":5,"rest_content":"a"},
{"id":6,"rest_content":"restapi"}]
增加一个启动脚本/usr/local/pgrest/startup.sh,如果有需要可以做成系统服务,不赘述。
vi /usr/local/pgrest/startup.sh
#!/bin/bash
start_time=$(date +%Y%m%d%H%M%S)
/usr/local/pgrest/bin/postgrest /usr/local/pgrest/cfg/default.conf > /usr/local/pgrest/log/log_postgrest_${start_time}.log