Skip to content

Instantly share code, notes, and snippets.

@mosdevly
Created March 13, 2020 17:55
Show Gist options
  • Save mosdevly/c8555189cc634c58b60e05e7fbe82ebc to your computer and use it in GitHub Desktop.
Save mosdevly/c8555189cc634c58b60e05e7fbe82ebc to your computer and use it in GitHub Desktop.
Flask with jQuery API Request Demo
{% extends 'base.html' %}
{% block content %}
<script src="{{ url_for('static', filename='js/example.js') }}"></script>
<div id="users">
</div>
{% endblock %}
$(function() {
const userDiv = $('#users');
$.get('api/users', (res) => {
for (user of res) {
console.log(user);
userDiv.append(`<li>${user.username}</li>`);
}
});
});
@app.route('/example')
def example():
"""Example of using sqlalchemy to return JSON."""
return render_template('example.html')
@app.route('/api/users')
def get_all_users():
"""Example of using sqlalchemy to return JSON."""
users = User.query.all()
return jsonify([u.serialize() for u in users])
@mosdevly
Copy link
Author

mosdevly commented Mar 13, 2020

This code assumes a base.html which had a head which includes a script tag to the jQuery CDN! Edit: it needs to be the full uncompressed version of jQuery.

It also assumes you need to serialize the sqlalchemy models. Here's an example of how you can do that:

class User(ModelMixin, db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(75), nullable=False)
    email = db.Column(db.String, unique=True)
    password = db.Column(db.String, nullable=False)

    def serialize(self):
        return {
            "id": self.id, "username": self.username,
            "email": self.email
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment