首页 > 技术文章 > 用Postman测试接口数据(CURD)

buildnewhomeland 2020-07-02 19:42 原文

置顶

一个不错的测试视频:https://www.imooc.com/learn/1048

一、模拟服务器接口

https://github.com/typicode/json-server
这个工具叫做 json-server

二、模拟数据

随便写一个json数据,起名为 db.json。

{
  "posts": [
    {
      "id": 1,
      "title": "json-server",
      "author": "typicode"
    }
  ],
  "comments": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ],
  "profile": {
    "name": "typicode"
  }
}

三、启动服务器

在 db.json 的目录下启动命令行工具,输入指令:

json-server --watch db.json


如果没报错就算成功了。
按照提示,访问 http://localhost:3000/posts 就能看到 db.json 中的 posts 字段下的数据;
同理,如果访问 http://localhost:3000/comments 就能看到 db.json 中的 comments 字段下的数据;
如果访问 http://localhost:3000/profile 就能看到 db.json 中的 profile 字段下的数据。

四、Postman 的下载安装

1. 下载安装 Postman( windows 64 位)

https://dl.pstmn.io/download/latest/win64

2. 注册账号并登录

用自己的邮箱注册一个,很方便。

五、Postman 的基本使用

登录进去,出现主页面。

(1) 找到搜索框下的 Collection,这里可以创建不同的文件夹,方便以后测试接口。

(2) 点击 New Collection,新建一个文件夹。

(3) 右击刚刚创建的 test 文件夹,添加一个请求。



(4) GET 方法

GET 方法用来查询数据,查找字段 posts 下的所有数据。(GET /posts)

如果查询 posts 下的第一条数据:/posts/1 (这个 1 是由数据中的 id 决定的。)

(5) POST 方法

POST 方法用来添加新数据,给 posts 下添加一条新数据。(POST /posts)
POST 方法上传的数据在 Body 中配置,选择第三个 x-www-form-urlencoded,将参数的键值分别写在 key 和 vlaue 中。


注意:id 不用配置进去,它会自动依次添加。

(6) PUT 方法

PUT 方法用来修改数据,修改 posts 下 id 为 2 的数据。(PUT /posts/2)
Body > x-www-form-urlencoded > data

(7) DELETE 方法

DELETE 方法用来删除数据,删除 posts 下 id 为 2 的数据。(DELETE /posts/2)

五、总结

  1. 创建文件夹便于分类
  2. 熟悉GET、POST、PUT、DELETE这些请求方法。
  3. 其中 POST 方法不可以直接上传到某一条具体的数据位置,POST /posts/1 会 404。

补充

1. 常见的 HTTP 状态码(status)

2. Restful 接口实例

推荐阅读