FastAPI - Beginner to Pro / Project 5 - Full Stack Application

FastAPI Full stack - Delete Todo

πŸ“ Introduction: Deleting a To-Do

In this lesson, we will add delete functionality to our to-do app.

This will allow users to remove tasks permanently from their list.

By the end of this tutorial, users will be able to delete any task directly from the edit page.


πŸ—οΈ Step 1: Add a Delete Button in the Edit To-Do Page

  1. Open edit-todo.html in the templates folder.

  2. Scroll to the bottom of the form where the "Edit To-Do" button and "Back" anchor tag are located.

  3. Add a new delete button between them:

<button id="delete-button" type="button" class="btn btn-danger">
  πŸ—‘οΈ Delete
</button>
  • ID: delete-button β€” used by JavaScript to attach functionality.

  • Class: btn btn-danger β€” gives it a red color to indicate deletion.

  • Text: Delete with a trash icon πŸ—‘οΈ for clarity.

  1. Save the file.


πŸ”„ Step 2: Implement Delete in JavaScript

  1. Open base.js in your static/js/ folder.

  2. Locate the edit to-do section of the code.

  3. Add a function to handle the delete button:

const deleteBtn = document.getElementById('delete-button');

if (deleteBtn) {
    deleteBtn.addEventListener('click', async () => {
        const todoId = /* fetch the current todo's ID, passed from template */;
        const token = document.cookie
            .split('; ')
            .find(row => row.startsWith('access_token='))
            .split('=')[1];

        const response = await fetch(`/todos/delete/${todoId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });

        if (response.ok) {
            window.location.href = '/todos/todo-page';
        } else {
            alert('Failed to delete to-do.');
        }
    });
}
  • Access Token: ensures only authorized users can delete tasks.

  • Redirect: after deletion, user is sent back to the home page.

  • Error Handling: shows an alert if deletion fails.


πŸš€ Step 3: Test the Delete Functionality

  1. Run your FastAPI application:

uvicorn app.main:app --reload
  1. Open your browser and sign in.

  2. Navigate to the Edit To-Do page of any task.

  3. Click the Delete πŸ—‘οΈ button.

  4. Verify:

    • The task is removed from the list.

    • You are redirected back to the to-do home page.


βœ… Step 4: Summary

  • Added a Delete button to the Edit To-Do page πŸ—‘οΈ.

  • Implemented JavaScript functionality to call the DELETE endpoint in FastAPI.

  • Users can now safely remove tasks, keeping their to-do list up-to-date.

  • The application now fully supports:

    • Creating To-Dos βž•

    • Editing To-Dos ✏️

    • Deleting To-Dos πŸ—‘οΈ

    • Marking as complete βœ…

    • Authentication & logout πŸ”

With this, your full-stack To-Do app is complete and functional.