Search code examples
pythondateflaskrestful-urlflask-restful

how to make get request url "api/reviews?start_date=mm-dd-yyyy&end_date=mm-dd-yyyy" in flask?


I am new to flask and I am building a restful api using flask .

class Review(Resource):
    def get(self, id = None):
        data = []
        if id:
            review_info = db.reviews.find_one({'_id': id})
            if review_info:
                return jsonify(review_info)
            else:
                return {"response": "no review found for {}".format(id)}

And My Routes Currently are

class Index(Resource):
    def get(self):
        return redirect(url_for("reviews"))

api = Api(app)
api.add_resource(Review, "/api/reviews/<int:id>", endpoint="id")

I want to create a get url "api/reviews?start_date=dd-mm-yyyy&end_date=dd-mm-yyyy" how can I do this? I don't want to create url of sort "api/start_date/../end_date/.."


Solution

  • This you can achieve by using marshmellow lib which will give you facility to read the query params inside your get request .Below is sample implementation for your request

    from marshmallow import Schema, fields
    class ReviewRequestFormat(Schema):
         start_date=fields.Str(required=True)
         end_date=fields.Str(required=True)
         id=fields.Str(required=True)
    
    class Review(Resource):
    @use_kwargs(ReviewRequestFormat)
    def get(self, **kwargs):
        id=kwargs.get('id')
        data = []
        if id:
            review_info = db.reviews.find_one({'_id': id})
            if review_info:
                return jsonify(review_info)
            else:
                return {"response": "no review found for {}".format(id)}
    

    your routes will be like below

     class Index(Resource):
        def get(self):
            return redirect(url_for("reviews"))
    
    api = Api(app)
    api.add_resource(Review, "/api/reviews/", endpoint="id")
    

    for more documentation on marshmallow you can refer -https://marshmallow.readthedocs.io/en/latest/