美文网首页python互动学习小组程序员
postman 测试rest-API 碰到的一些问题

postman 测试rest-API 碰到的一些问题

作者: sunlin1234 | 来源:发表于2016-12-29 21:33 被阅读3865次

    首先来了解一下postman,postman 是谷歌浏览器的一个插件,它可以用来充当客户端测试API接口
    它提供相应的get/post/put/delete/等常用的请求方法
    设置Content-Type格式,以及提供认证支持,非常nice。
    来看一下他的界面

    Paste_Image.png

    ![1DT3TP}$REDB$BGSYA]$UQJ.png](https://img.haomeiwen.com/i1516470/c860504f76c08c51.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    ![8]S1GHCVTB@C]B1ZI{SBT}Q.png](https://img.haomeiwen.com/i1516470/63941f7ad4c86330.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    82`(DYPMJ95SY7EO68)8D}H.png 0NO`K7P_SUBJ}PONG{7EVOL.png

    简单的了解完postman的工具以后,现在我说说我自己的遇到的错误。
    我使用python flask 框架来书写rest-API 写了相应的路由但是呢在post提交数据的时候出现了一直报错400 的错误。
    先来看一下我的代码:


    、、、
    //post请求的代码
    @app.route('/api/users',methods=['POST'])
    def create_user():
    if not request.json or not 'username' in request.json:
    abort(400)
    user = {
    'id':users[-1]['id'] + 1,
    'username':request.json['username'],
    'password':request.json['password']
    }
    users.append(user)
    return jsonify({'user':user}), 201
    、、、


    (注意源代码是有缩进的)这段代码看起来一点问题也没有,那么我问在哪呢?
    在postman中我将提交数据的格式使用的是form表单提交的,但是呢在代码中我是用request.json来请求的,提交和请求的格式不一致导致了出错。!!当然了要解决这个问题有两种方式第一种:是提交的时候postman中HEADERS使用的Content-Type 修改为application/json 并且Body中选中raw,写数据,第二种:将代码中的request.json修改为表单请求方式,request.form来接收表单数据,Headers中使用from-data或者x-www-form-urlencode 同时写数据。

    最后成功了。

    0E}Q1@D51DE_{Q@VSNUAU4Y.png

    get一下结果

    Paste_Image.png

    哇塞出来了!

    补一些概念:
    Content-Type:Content-Type,内容类型,一般是指网页中存在的Content-Type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件,这就是经常看到一些Asp网页点击的结果却是下载到的一个文件或一张图片的原因

    关于更多消息体的编码格式可以参考这里(https://imququ.com/post/four-ways-to-post-data-in-http.html

    相关文章

      网友评论

      • messiGao:使用postman选择form-data提交错误,什么原因
        "timestamp": 1496063505828,
        "status": 415,
        "error": "Unsupported Media Type",
        "exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
        "message": "Invalid mime type \"from-data\": does not contain '/'",
        "path": "/user"
        sunlin1234: @messiGao 什么意思?

      本文标题:postman 测试rest-API 碰到的一些问题

      本文链接:https://www.haomeiwen.com/subject/rnzuvttx.html