I have some RESTful API calls in web2py which take in JSON file. I make the calls through the command line using curl like:
curl -H "Content-Type: application/json" --data @mydata.json https://mywebsite/doWork
In my web2py controller I have it setup to read the POST request. When I examine request.vars by returning it, it contains the full JSON data, but request.vars is of type: class 'gluon.storage.Storage'.
I need the data in string format in the controller. However, if I do str(request.vars), web2py appends a Storage tag in front of my data.
@request.restful()
def doWork():
def POST(*args, **vars):
return(request.vars)
return locals()
Assuming the mydata.json file is something simple like:
{ "key": "value" }
The request to POST will return {"key": "value"} as a gluon.storage.Storage object.
If I change the line return(request.vars) to return(str(request.vars)) the output is now: < Storage {u'key': u'value'}>
How can I convert this request.vars to a string without it appending the Storage tag to the front, and changing the double quotes to single quotes?
If you want to convert vars
back to JSON, you can use the Python json
library or just use response.json
:
return response.json(vars)
Alternatively, you can add the .json
extension to the request and simply return vars
directly:
return vars
with the following request:
curl -H "Content-Type: application/json" --data @mydata.json https://mywebsite/doWork.json
In that case, web2py will automatically convert the response to JSON.