Code for How to Create a RESTful API with Flask in Python Tutorial

View on Github

from flask import Flask
from flask_restful import Api
from models import db
import config
from resources import TaskList

# Create the Flask application and the Flask-RESTful API manager.
app = Flask(__name__)
# Initialize the Flask-SQLAlchemy object.
# Create the Flask-RESTful API manager.
api = Api(app)
# Create the endpoints.
api.add_resource(TaskList, '/tasks')

if __name__ == '__main__':
    # Create the database tables.
    with app.app_context():
    # Start the Flask development web server.

from flask_restful import Resource
from flask import request
from models import Task, db

class TaskList(Resource):
    def get(self):
        # Get all the tasks from the database.
        tasks = Task.query.all()
        # Convert the tasks to JSON and return a response.
        task_list = [{'id':, 'description': task.description} for task in tasks]
        return {'tasks': task_list}

    def post(self):
        # Get the JSON data from the request.
        task_data = request.get_json()
        # Check if the data is valid.
        if not task_data:
            return {'message': 'No input data provided'}, 400
        description = task_data.get('description')
        if not description:
            return {'message': 'Description is required'}, 400
        # Add the task to the database.
        new_task = Task(description=description)
        # Commit the task to the database.
        # Return a message to the user.
        return {'message': 'Task added', 'task': {'id':, 'description': new_task.description}}

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Task(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(200), nullable=False) # nullable=False means that the column cannot be empty

    def __repr__(self):
        # This method is used to print the object.
        return f'Task {}: {self.description}'

SQLALCHEMY_DATABASE_URI = 'sqlite:///tasks.db'