dbrest api 调用说明(含样例代码)

Posted by Henry on 10-18,2020

本系列其他文章

dbrest v1.1公测版发布
dbrest配置说明
dbrestapi调用说明含样例代码
dbrest lua脚本模板
dbrest小试牛刀
dbrest压测结果

dbrest api 调用说明

前期准备工作

假定您对外发布了你的学生信息表students,
表中主要包含如下列

字段说明
id自增主键
name姓名
gender性别
age年龄
class班级
logondate注册日期
remark备注
remark2备注2
height身高
weight体重
deleted_flag注销状态

如果不存在此表,可以用如下语句建表并插入几条记录
建表语句:

CREATE TABLE `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
  `name` varchar(20) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '姓名',
  `gender` varchar(10) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '性别',
  `age` int(11) NOT NULL COMMENT '年龄',
  `class` varchar(20) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '班级',
  `remark` varchar(45) COLLATE utf8mb4_bin DEFAULT NULL,
  `remark2` longtext COLLATE utf8mb4_bin,
  `logondate` datetime DEFAULT NULL,
  `createdate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `height` decimal(18,2) DEFAULT NULL,
  `weight` float DEFAULT NULL,
  `deleted_flag` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

插入几条记录

INSERT INTO `db1`.`students` (`name`, `gender`, `age`, `class`, `logondate`) VALUES ('张三', '男', '20', '三班', '2017-03-01');
INSERT INTO `db1`.`students` (`name`, `gender`, `age`, `class`, `logondate`) VALUES ('张四', '男', '19', '四班', '2017-03-01');
INSERT INTO `db1`.`students` (`name`, `gender`, `age`, `class`, `logondate`) VALUES ('王五', '男', '22', '三班', '2017-03-01');
INSERT INTO `db1`.`students` (`name`, `gender`, `age`, `class`, `logondate`) VALUES ('张娜', '女', '20', '三班', '2017-09-01');
INSERT INTO `db1`.`students` (`name`, `gender`, `age`, `class`, `logondate`) VALUES ('李娜', '女', '16', '三班', '2017-09-01');
INSERT INTO `db1`.`students` (`name`, `gender`, `age`, `class`, `logondate`) VALUES ('王娜', '女', '20', '四班', '2017-09-01');

http get 对应sql的select

dbrest api数据查询采用http get方式
查询条件放在url查询参数中
查询格式为:<column>=<operator>.<value>
多个查询条件用 “&”连接起来
查询条件操作符采用类似mongodb的操作符,区别于mongodb用冒号":"分割操作符与操作数,dbrest采用句点号“.”来分割操作符与操作数。
支持like模糊查询: 用"*" 代替 sql中的 “%”
支持in 查询 <column>=in."<value1>","<value2>","<value3>"
例子:
1.查询所有学生信息
http://127.0.0.1:9000/api/students
2. 查询姓名为"张三"的学生信息
http://127.0.0.1:9000/api/students?name=eq.张三
3. 查询年龄=16的女生信息
http://127.0.0.1:9000/api/students?age=eq.16&gender=eq.女
4. 模糊查询年龄>16的,姓张的学生信息
http://127.0.0.1:9000/api/students?age=gt.16&name=like.张*
5. 查询三班与四班的,所有张姓的学生信息
http://127.0.0.1:9000/api/students?name=like.张*&class=in."三班","四班"

dbrest api 查询语法规则

操作符dbrest格式dbrest范例SQL范例mongodb格式mongodb范例
等于<column>=eq.<value>name=eq.李刚where name='李刚'{<key>:<value>}db.col.find({"name":"李刚"}).pretty()
小于<column>=lt.<value>age=lt.20where age< 20{<key>:{$lt:<value>}}db.col.find({"age":{$lt:20}}).pretty()
小于或等于<column>=lte.<value>age=lte.20where age<= 20{<key>:{$lte:<value>}}db.col.find({"age":{$lte:20}}).pretty()
大于<column>=gt.<value>age=gt.20where age>20{<key>:{$gt:<value>}}db.col.find({"age":{$gt:20}}).pretty()
大于或等于<column>=gte.<value>age=gte.20where age >= 20{<key>:{$gte:<value>}}db.col.find({"age":{$gte:20}}).pretty()
不等于<column>=lte.<value>age=neq.20where age <> 20{<key>:{$ne:<value>}}db.col.find({"age":{$ne:20}}).pretty()
空值<column>=is.nullremark=is.nullwhere remark is null{<key>:{$eq:null}}db.col.find( { "remark": { $eq: null } } )
非空值<column>=not.is.nullremark=not.is.nullwhere remark is not null{<key>:{$ne:null}}db.col.find( { "remark": { $ne: null } } )
模糊查询<column>=like.<value>name=like.李*where name like '李%'
In查询<column>=in.<value>name=in."张三","李四"where name in('张三','李四')
多条件组合 age=lte.20&name=like.李*where age<= 20 and name like '李%'

小图
image.png

注意:数据库增删改需要dbrest配置权限

客户端调用时提供对应的Authorization,dbrest默认采用Basic Authorization.关于权限管理参考配置说明与样例代码

http post 对应sql的Insert

例子:插入一条学生信息
post http://127.0.0.1:9000/api/students
Content-Type: application/json; charset=UTF-8
--body部分---
{"name":"李四","gender":"男","age":20,"class":"一班"}

http patch 对应sql的Update

例子:修改id=5的学生的备注信息
patch http://127.0.0.1:9000/api/students?id=eq.5
Content-Type: application/json; charset=UTF-8
--body部分---
{"remark":"修改一下哟"}

http delete 对应sql的delete

例子:删除id=5的学生信息
delete http://127.0.0.1:9000/api/students?id=eq.5

Sample代码(python版)

import requests
from requests.auth import HTTPBasicAuth
import datetime
import hashlib
import json

#在线部署版URL
#baseUrl = "https://www.infoswap.cn/api"
baseUrl = "http://127.0.0.1:9000/api"

#1.查询所有学生信息
r = requests.get(baseUrl+"/students")
print('查询所有->',r.text)

#2.查询姓名为"张三"的学生信息
r = requests.get(baseUrl+"/students", params={"name":"eq.张三"})
print('查询姓名为"张三"的学生信息->',r.text)

#3.查询年龄=16的女生信息
r = requests.get(baseUrl+"/students", params={"age":"eq.16","gender":"eq.女"})
print('查询年龄=16的女生信息->',r.text)

#4.模糊查询年龄>16的,姓张的学生信息
r = requests.get(baseUrl+"/students", params={"age":"gt.16","name":"like.张*"})
print('模糊查询年龄>16的,姓张的学生信息->',r.text)

#5.查询三班与四班的,所有张姓的学生信息
r = requests.get(baseUrl+"/students", params={"name":"like.张*","class":"in.\"三班\",\"四班\""})
print('查询三班与四班的,所有张姓的学生信息->',r.text)

#账户信息,(确保dbrest配置文件conf.xml中配置了此账号)
AccessKey = "client1"
AccessSecret = "abcde"


#dbrest AuthType缺省配置为BasicAuth,代码示例
_headers ={'Content-Type':'application/json;charset=utf-8'}
#Insert
r = requests.post(baseUrl+"/students", headers=_headers, data=json.dumps({"name":"李四","gender":"男","age":20,"class":"一班","logondate":"2020-09-02"},ensure_ascii=False).encode("utf-8"), auth=(AccessKey,AccessSecret))
print("status_code->",r.status_code,", text->",r.text)

#Update
r = requests.patch(baseUrl+"/students", params={"id":"eq.8"}, headers=_headers, data='{"remark":"修改备注","logondate":"2020-12-02","deleted_flag":1}'.encode('utf-8'), auth=(AccessKey,AccessSecret))
print("status_code->",r.status_code,", text->",r.text)


#Delete,此处故意错写成-7,不想被删除,否则无法做查询演示了
r = requests.delete(baseUrl+"/students", params={"id":"gt.7"},auth=(AccessKey,AccessSecret))
print("status_code->",r.status_code,", text->",r.text)

#如果conf.xml中配置了<NeedAuth>true<NeedAuth>,表示http get 操作也需要用户鉴权,调用时加上鉴权信息
r = requests.get(baseUrl+"/students",auth=(AccessKey,AccessSecret))
print('查询所有->',r.text)

#dbrest AuthType配置为 MD5Auth时 代码示例
'''
#当前时间,时间格式yyyyMMddHHmmss
AccessKey = "client1"
AccessSecret = "abcde"
clienttime =  datetime.datetime.now().strftime('%Y%m%d%H%M%S')
concatedStr = AccessKey + clienttime + AccessSecret
md5Sign = hashlib.md5(concatedStr.encode()).hexdigest()
_headers ={'AccessKey': 'client1', 'clienttime': clienttime, 'Authorization': md5Sign, 'Content-Type':'application/json;charset=utf-8'}

#Insert
r = requests.post(baseUrl+"/students", headers=_headers, data=json.dumps({"name":"李四","gender":"男","age":20,"class":"一班","logondate":"2020-09-02"},ensure_ascii=False).encode("utf-8"))
print("status_code->",r.status_code,", text->",r.text)

#Update
r = requests.patch(baseUrl+"/students", params={"id":"eq.5"}, headers=_headers, data='{"remark":"修改备注"}'.encode('utf-8'))
print("status_code->",r.status_code,", text->",r.text)

#Delete,此处故意错写成-5,不想被删除,否则无法做查询演示了
r = requests.delete(baseUrl+"/students", params={"id":"eq.-5"}, headers=_headers)
print("status_code->",r.status_code,", text->",r.text)


#如果conf.xml中配置了<NeedAuth>true<NeedAuth>,表示http get 操作也需要用户鉴权,调用时加上鉴权信息
r = requests.get(baseUrl+"/students", headers=_headers)
print('查询所有->',r.text)
'''