mock:json-server使用教程

简介:json-server是一款mock工具,支持前端本地运行,可以存储json数据的充当server,搭建非常简便,适合对数据进行简单的增删改查。

github地址

https://github.com/typicode/json-server

json-server网址:

https://www.npmjs.com/package/json-server

安装:相关攻略nodejs:win10安装nodejs:centos7-docker安装

npm install -g json-server

检查版本:

json-server -v

图片

新建json数据:保存格式为data.json

{
  "user": [
    {
      "id": 1,
      "name": "tom1",
      "age": "21"
    },
    {
      "id": 2,
      "name": "tom2",
      "age": "22"
    }
  ],
  "grade":{
      "score": 100,
      "user_id": "10001",
      "grade": "A"
    }
}

在data.json文件下进入命令行模式:
例如:D:\codes\tools

cd D:\codes\tools
json-server --watch --port 3001 data.json

访问服务主页:
http://localhost:3001/
图片
图片

增删改查:

import requests

# 获取 用户列表
url = "http://localhost:3001/user"
user = requests.get(url).json()
print("初始用户列表:", user)

# 获取 单个用户
data = {"name": "tom1"}
user_tom1 = requests.get(url, data=data).json()
print("获取单个用户", user_tom1)

# 增加用户
data = {"id": 3, "name": "tom3", "age": 23}
result_ = requests.post(url, data=data).json()
print("增加用户:", result_)

# 获取 用户列表
url = "http://localhost:3001/user"
user = requests.get(url).json()
print("新增后用户列表:", user)

# 删除用户
delete_url = "http://localhost:3001/user/2"
result = requests.delete(delete_url).json()
print("删除用户:", result)

# 获取 用户列表
url = "http://localhost:3001/user"
user = requests.get(url).json()
print("删除后用户列表:", user)

# 修改等级信息 = 全量
put_url = "http://localhost:3001/grade"
put_data = {"score": 60, "user_id": "20001", "grade": "D"}
result = requests.put(put_url, data=put_data).json()
print("全量修改等级:", result)

# 获取 等级
url = "http://localhost:3001/grade"
user = requests.get(url).json()
print("全量修改后等级:", user)

# 修改用户 = 局部
patch_url = "http://localhost:3001/grade"
patch_data = {"score": 90, "user_id": "20001", "grade": "B"}
result = requests.patch(patch_url, data=patch_data).json()
print("局部修改等级:", result)

# 获取 等级
url = "http://localhost:3001/grade"
user = requests.get(url).json()
print("局部修改后等级:", user)

代码执行结果:
图片
json-server响应结果:
图片

json-server内置过滤:

1、http://localhost:3001/user 访问的是data.json文件下的所有内容。

2、http://localhost:3001/user?name= 模拟接口参数可筛选该目录下内容。

3、分页查询 参数为 _start, _end, _limit,并可添加其它参数筛选条件

如:http://localhost:3001/user?_start=1&_limit=2

http://localhost:3001/user?_start=1&_end=2

4、排序 参数为_sort, _order

如:http://localhost:3001/user?_sort=id&_order=asc

http://localhost:3001/users?_sort=name,views&_order=desc,asc

5、操作符 _gte, _lte, _ne, _like

_gte大于,_lte小于, _ne非, _like模糊查询

6、q全局搜索(模糊查询)
image.gif

参数列表:

图片

图片

微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值