Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't return json pagination in flask for REST API

I'm working with Miguel Grinberg's Flask REST API repo, and I'm failing to return JSON paginated results. The examples online use html templates, but I just want to return a number of results (20), and eventually return links for the previous and next pages. When I return the code immediately following this sentence, I get "pagination object is not iterable":

def get_customers():
    return jsonify({'customers': [customer.get_url() for customer in
                                  Customer.query.paginate(page=1, per_page=1)]})

I understand I'm passing the wrong object, but I'm not sure if I should use another module, or if I'm on the right path. Does anyone have a suggestion to reach my end goal?

The original code in Miguel's repo is:

@app.route('/customers/', methods=['GET'])
def get_customers():
    return jsonify({'customers': [customer.get_url() for customer in
                                  Customer.query.all()]})

The whole file is here: https://github.com/miguelgrinberg/oreilly-flask-apis-video/blob/a460ad9df2e58c13b90f183e81b4e8953eb186cb/orders/api.py

The relevant code I'm working with:

class Customer(db.Model):
    __tablename__ = 'customers'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True)

    def get_url(self):
        return url_for('get_customer', id=self.id, _external=True)

    def export_data(self):
        return {
            'self_url': self.get_url(),
            'name': self.name
        }

    def import_data(self, data):
        try:
            self.name = data['name']
        except KeyError as e:
            raise ValidationError('Invalid customer: missing ' + e.args[0])
        return self


@app.route('/customers/', methods=['GET'])
def get_customers():
    return jsonify({'customers': [customer.get_url() for customer in
                                  Customer.query.paginate(page=1, per_page=1)]})

@app.route('/customers/<int:id>', methods=['GET'])
def get_customer(id):
    return jsonify(Customer.query.get_or_404(id).export_data())
like image 737
SO03112 Avatar asked Oct 26 '25 06:10

SO03112


1 Answers

See the API docs.

If you want to iterate over a Pagination object, use (for example)

 Customer.query.paginate(page=1, per_page=1).items

which is a collection of the items for that page.

like image 110
jfowkes Avatar answered Oct 28 '25 19:10

jfowkes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!