I just wrote an echo server that responds to curl requests with the method used and the data sent. Sticking to GET and POST for now, but I would like to know if there's something I can do to improve my RESTful API.
I'm supposed to:
- Only be able to call the
/data
endpoint - Only allow JSON parameters
- Use best practices of coding a RESTful API
Expected JSON response:
{
"method": <HTTP METHOD REQUESTED>,
"data": <HTTP PARAMETERS SENT IN THE REQUEST>
}
Here is my current code:
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)
Everything seems to work fine for now. I'm looking to improve my code so any feedback is appreciated.