Created
October 30, 2024 21:41
-
-
Save jonasbjork/5596471295fa97d7b12869639f0ae594 to your computer and use it in GitHub Desktop.
Ett exempel: ett enkelt TODO-api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, jsonify, request | |
import sqlite3 | |
app = Flask(__name__) | |
def init_db(): | |
with sqlite3.connect('todo.db') as conn: | |
cursor = conn.cursor() | |
cursor.execute('''CREATE TABLE IF NOT EXISTS todos ( | |
id INTEGER PRIMARY KEY AUTOINCREMENT, | |
title TEXT NOT NULL, | |
completed BOOLEAN NOT NULL CHECK (completed IN (0, 1)) | |
)''') | |
conn.commit() | |
init_db() | |
@app.route('/todo', methods=['POST']) | |
def create_todo(): | |
data = request.get_json() | |
title = data.get('title') | |
with sqlite3.connect('todo.db') as conn: | |
cursor = conn.cursor() | |
cursor.execute('INSERT INTO todos (title, completed) VALUES (?, ?)', (title, False)) | |
conn.commit() | |
new_task_id = cursor.lastrowid | |
return jsonify({'id': new_task_id, 'title': title, 'completed': False}), 201 | |
@app.route('/todo', methods=['GET']) | |
def get_todos(): | |
with sqlite3.connect('todo.db') as conn: | |
cursor = conn.cursor() | |
cursor.execute('SELECT * FROM todos') | |
todos = cursor.fetchall() | |
todo_list = [{'id': row[0], 'title': row[1], 'completed': bool(row[2])} for row in todos] | |
return jsonify(todo_list), 200 | |
@app.route('/todo/<int:todo_id>', methods=['PUT']) | |
def mark_completed(todo_id): | |
with sqlite3.connect('todo.db') as conn: | |
cursor = conn.cursor() | |
cursor.execute('UPDATE todos SET completed = ? WHERE id = ?', (True, todo_id)) | |
if cursor.rowcount == 0: | |
return jsonify({'error': 'Task not found'}), 404 | |
conn.commit() | |
return jsonify({'id': todo_id, 'completed': True}), 200 | |
@app.route('/todo/<int:todo_id>', methods=['DELETE']) | |
def delete_todo(todo_id): | |
with sqlite3.connect('todo.db') as conn: | |
cursor = conn.cursor() | |
cursor.execute('DELETE FROM todos WHERE id = ?', (todo_id,)) | |
if cursor.rowcount == 0: | |
return jsonify({'error': 'Task not found'}), 404 | |
conn.commit() | |
return jsonify({'message': 'Task deleted'}), 200 | |
if __name__ == '__main__': | |
app.run(debug=True) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment