如何用瓶子改善回声服务器

时间:2019-02-12 19:41:09

标签: python rest api

我刚刚编写了一个echo服务器,该服务器使用所使用的方法和发送的数据来响应curl请求。现在仍坚持使用GET和POST,但我想知道是否可以做些事情来改善我的RESTFUL API

应该:

 1. Only be able to call the /data endpoint
 2. Only allow JSON parameters 
 3. Use best practices of coding a restful API

预期的JSON响应:

{
  “method”: <HTTP METHOD REQUESTED>,
  “data”: <HTTP PARAMETERS SENT IN THE REQUEST>
}

这是我当前的代码:

from bottle import run, post, request, response, get, route, put, delete
from json import dumps
import json

@get('/data')
def data():
    #if headers are not specified we can check if body is a json the following way
    #postdata = request.body.read()
    postdata = request.json
    try:
        #rv = {"method": request.method, "data": json.loads(postdata.decode('utf-8'))}
        rv = {"method": request.method, "data": postdata}
    except:
        raise ValueError
    response.content_type = 'application/json'
    return dumps(rv)

@post('/data')
def data():
    #postdata = request.body.read()
    postdata = request.json
    try:
        #rv = {"method": request.method, "data": json.loads(postdata.decode('utf-8'))}
        rv = {"method": request.method, "data": postdata}
    except:
        raise ValueError
    response.content_type = 'application/json'
    return dumps(rv)

目前一切似乎都正常,我正在尝试取得一个好成绩,因此,如果有什么可以改善的建议

0 个答案:

没有答案