Skip to content

Instantly share code, notes, and snippets.

@Babatunde13
Last active March 31, 2024 08:41
Show Gist options
  • Select an option

  • Save Babatunde13/81866103136d20090a6f5c17f5de336b to your computer and use it in GitHub Desktop.

Select an option

Save Babatunde13/81866103136d20090a6f5c17f5de336b to your computer and use it in GitHub Desktop.

Revisions

  1. Babatunde13 revised this gist Dec 11, 2020. 1 changed file with 0 additions and 29 deletions.
    29 changes: 0 additions & 29 deletions app.py
    Original file line number Diff line number Diff line change
    @@ -204,34 +204,5 @@ def delete_todo(id):
    'success': 'Data deleted successfully'
    }

    @app.errorhandler(400)
    def bad_request(e):
    return {
    'error': 'Bad Request',
    'message': 'You tried to send somenthing the server did not understand'
    }, 400

    @app.errorhandler(404)
    def not_found(e):
    return {
    'error': 'Endpoint not found',
    'message': 'The path/ resource is not found on the server'
    }, 404

    @app.errorhandler(405)
    def method_not_allowed(e):
    return {
    'error': 'Method is not allowed',
    'message': 'This method is not defined for this endpoint'
    }, 405

    @app.errorhandler(500)
    def server_error(e):
    db.session.rollback()
    return {
    'error': 'Server error',
    'message': 'Something went wrong'
    }, 500

    if __name__ == '__main__':
    app.run()
  2. Babatunde13 created this gist Dec 8, 2020.
    237 changes: 237 additions & 0 deletions app.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,237 @@
    from flask import Flask, jsonify, request
    from flask_sqlalchemy import SQLAlchemy
    import uuid

    app = Flask(__name__)
    db = SQLAlchemy(app)

    app.config['SECRET_KEY']='secret'
    app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///app.db'

    class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, index=True)
    name = db.Column(db.String(20), nullable=False)
    email = db.Column(db.String(28), nullable=False, unique=True)
    public_id = db.Column(db.String, nullable=False)
    is_admin = db.Column(db.Boolean, default=False)
    todos=db.relationship('Todo', backref='owner', lazy='dynamic')

    def __repr__(self):
    return f'User <{self.email}>'

    class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True, index=True)
    name = db.Column(db.String(20), nullable=False)
    is_completed = db.Column(db.Boolean, default=False)
    public_id = db.Column(db.String, nullable=False)
    user_id=db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
    return f'Todo: <{self.name}>'


    @app.route('/')
    def home():
    return {
    'message': 'Welcome to building RESTful APIs with Flask and SQLAlchemy'
    }


    @app.route('/users/')
    def get_users():
    return jsonify([
    {
    'id': user.public_id, 'name': user.name, 'email': user.email,
    'is admin': user.is_admin
    } for user in User.query.all()
    ])

    @app.route('/users/<id>/')
    def get_user(id):
    print(id)
    user = User.query.filter_by(public_id=id).first_or_404()
    return {
    'id': user.public_id, 'name': user.name,
    'email': user.email, 'is admin': user.is_admin
    }

    @app.route('/users/', methods=['POST'])
    def create_user():
    data = request.get_json()
    if not 'name' in data or not 'email' in data:
    return jsonify({
    'error': 'Bad Request',
    'message': 'Name or email not given'
    }), 400
    if len(data['name']) < 4 or len(data['email']) < 6:
    return jsonify({
    'error': 'Bad Request',
    'message': 'Name and email must be contain minimum of 4 letters'
    }), 400
    u = User(
    name=data['name'],
    email=data['email'],
    is_admin=data.get('is admin', False),
    public_id=str(uuid.uuid4())
    )
    db.session.add(u)
    db.session.commit()
    return {
    'id': u.public_id, 'name': u.name,
    'email': u.email, 'is admin': u.is_admin
    }, 201

    @app.route('/users/<id>/', methods=['PUT'])
    def update_user(id):
    data = request.get_json()
    if 'name' not in data:
    return {
    'error': 'Bad Request',
    'message': 'Name field needs to be present'
    }, 400
    user = User.query.filter_by(public_id=id).first_or_404()
    user.name=data['name']
    if 'is admin' in data:
    user.is_admin=data['admin']
    db.session.commit()
    return jsonify({
    'id': user.public_id,
    'name': user.name, 'is admin': user.is_admin,
    'email': user.email
    })

    @app.route('/users/<id>/', methods=['DELETE'] )
    def delete_user(id):
    user = User.query.filter_by(public_id=id).first_or_404()
    db.session.delete(user)
    db.session.commit()
    return {
    'success': 'Data deleted successfully'
    }

    @app.route('/todos/')
    def get_todos():
    return jsonify([
    {
    'id': todo.public_id, 'name': todo.name,
    'owner': {
    'name': todo.owner.name,
    'email': todo.owner.email,
    'public_id': todo.owner.public_id
    }
    } for todo in Todo.query.all()
    ])

    @app.route('/todos/<id>')
    def get_todo(id):
    todo = Todo.query.filter_by(public_id=id).first_or_404()
    return jsonify({
    'id': todo.public_id, 'name': todo.name,
    'owner': {
    'name': todo.owner.name,
    'email': todo.owner.email,
    'public_id': todo.owner.public_id
    }
    })

    @app.route('/todos/', methods=['POST'])
    def create_todo():
    data = request.get_json()
    if not 'name' in data or not 'email' in data:
    return jsonify({
    'error': 'Bad Request',
    'message': 'Name of todo or email of creator not given'
    }), 400
    if len(data['name']) < 4:
    return jsonify({
    'error': 'Bad Request',
    'message': 'Name of todo contain minimum of 4 letters'
    }), 400

    user=User.query.filter_by(email=data['email']).first()
    if not user:
    return {
    'error': 'Bad request',
    'message': 'Invalid email, no user with that email'
    }
    is_completed = data.get('is completed', False)
    todo = Todo(
    name=data['name'], user_id=user.id,
    is_completed=is_completed, public_id=str(uuid.uuid4())
    )
    db.session.add(todo)
    db.session.commit()
    return {
    'id': todo.public_id, 'name': todo.name,
    'completed': todo.is_completed,
    'owner': {
    'name': todo.owner.name,
    'email': todo.owner.email,
    'is admin': todo.owner.is_admin
    }
    }, 201

    @app.route('/todos/<id>/', methods=['PUT'])
    def update_todo(id):
    data = request.get_json()
    print(data)
    print('is completed' in data)
    if not 'name' in data or not 'completed' in data:
    return {
    'error': 'Bad Request',
    'message': 'Name or completed fields need to be present'
    }, 400
    todo = Todo.query.filter_by(public_id=id).first_or_404()
    todo.name=data.get('name', todo.name)
    if 'is completed' in data:
    todo.is_completed=data['is completed']
    db.session.commit()
    return {
    'id': todo.public_id, 'name': todo.name,
    'is completed': todo.is_completed,
    'owner': {
    'name': todo.owner.name, 'email': todo.owner.email,
    'is admin': todo.owner.is_admin
    }
    }, 201

    @app.route('/todos/<id>/', methods=['DELETE'] )
    def delete_todo(id):
    todo = Todo.query.filter_by(public_id=id).first_or_404()
    db.session.delete(todo)
    db.session.commit()
    return {
    'success': 'Data deleted successfully'
    }

    @app.errorhandler(400)
    def bad_request(e):
    return {
    'error': 'Bad Request',
    'message': 'You tried to send somenthing the server did not understand'
    }, 400

    @app.errorhandler(404)
    def not_found(e):
    return {
    'error': 'Endpoint not found',
    'message': 'The path/ resource is not found on the server'
    }, 404

    @app.errorhandler(405)
    def method_not_allowed(e):
    return {
    'error': 'Method is not allowed',
    'message': 'This method is not defined for this endpoint'
    }, 405

    @app.errorhandler(500)
    def server_error(e):
    db.session.rollback()
    return {
    'error': 'Server error',
    'message': 'Something went wrong'
    }, 500

    if __name__ == '__main__':
    app.run()