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


View on Github

app.py

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__)
app.config.from_object(config)
# Initialize the Flask-SQLAlchemy object.
db.init_app(app)
# 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():
        db.create_all()
    # Start the Flask development web server.
    app.run(debug=True)

resources.py

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': task.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)
        db.session.add(new_task)
        # Commit the task to the database.
        db.session.commit()
        # Return a message to the user.
        return {'message': 'Task added', 'task': {'id': new_task.id, 'description': new_task.description}}

models.py

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.id}: {self.description}'

config.py

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