0

I am writing an API using flask.

I would like the API to return either the elements in the column category or in the column subcategory of my table category depending on the url.

eg http:.../categories/subcategory or http:.../categories/category

I have tried to create the variable category_type and to assign it to the output d but it does not work.

 class Categories(db.Model):
      __tablename__ = 'categories'
      category = db.Column(db.Text)
      subcategory = db.Column(db.Text, primary_key = True)

 @app.route('/categories/<string:category_type>', methods=['GET'])
 def categories(category_type):
     if request.method == 'GET':
         results = Categories.query.all()

         json_results = []
         for result in results:
             d = {'Category': result.category_type}
             json_results.append(d)

         return jsonify(items=json_results)
3
  • result.category_type isn't defined in the Categories class. Perhaps you want a filter? Commented Jun 30, 2015 at 21:33
  • 'Category': category_type should be enough Commented Jun 30, 2015 at 21:34
  • unfortunately not it returns the name of the column in my db but I would like the content Commented Jun 30, 2015 at 21:38

1 Answer 1

1

Change categories method similar below:

@app.route('/categories/<string:category_type>', methods=['GET'])
def categories(category_type):
    if category_type.lower() not in ('category', 'subcagory'):
        flask.abort(404)

    if request.method == 'GET':
        results = Categories.query.all()

        json_results = []
        for result in results:
            d = {'Category': getattr(result, category_type.lower())}
            json_results.append(d)

        return jsonify(items=json_results)

Update: if you want remove duplicates change json_results variable type to set similar below:

@app.route('/categories/<string:category_type>', methods=['GET'])
def categories(category_type):
    if category_type.lower() not in ('category', 'subcagory'):
        flask.abort(404)

    if request.method == 'GET':
        results = Categories.query.all()

        json_results = set()
        for result in results:
            d = {'Category': getattr(result, category_type.lower())}
            json_results.add(d)

        return jsonify(items=json_results)
Sign up to request clarification or add additional context in comments.

1 Comment

Is there any chance you could tell me how to remove duplicates?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.