This is how I want to call my REST API filtering on date range:
curl "127.0.0.1:5000/report?start=10%2F06%2F2015%2007%3A00%3A00&end=10%2F07%2F2015%2006%3A59%3A59"
where %2F is forward slash and %3A is colon
On parsing this URL here: http://www.freeformatter.com/url-parser-query-string-splitter.html I'm getting correct fields
This is the script I have so far:
from flask import Flask
from flask_restful import Resource, Api
from flask_restful import reqparse
from sqlalchemy import create_engine
e = create_engine("x")
parser = reqparse.RequestParser()
parser.add_argument('start', type = str)
parser.add_argument('end', type = str)
app = Flask(__name__)
api = Api(app)
class Report(Resource):
def get(self):
args = parser.parse_args()
conn = e.connect()
stat = """
select id from report where dates between ? and ?
"""
query = conn.execute(stat, [[args[0], args[1]])
for i in query.cursor.fetchall():
return {'id': i[0]}
api.add_resource(Report, '/report')
if __name__ == '__main__':
app.run()
This is the error I'm getting:
C:\Users\x> curl "127.0.0.1:5000/report?start=10%2F06%2F2015%2007%3A00%3A00&end=10%2F07%2F2015%2006%3A59%3A59" {"message": "an integer is required (got type str)"}
I suspect your problem is that you're accessing a dict (args) by index. Reqparse creates a dictionary, not an array. You should access your parameters using args['start']
and args['end']
.
Your line would look like this:
query = conn.execute(stat, [args['start'], args['end']])
Additionally, your return is not correct. Change return {'id': i[0]}
to return {'id': i}
since i
in this case is not an array.
One last thing, I highly suggest using http://pythonhosted.org/Flask-SQLAlchemy/ instead of using raw SQL queries.