Creating a Task Manager API with Django and MySQL

msnmongare

Sospeter Mong'are

Posted on October 19, 2023

Creating a Task Manager API with Django and MySQL

Introduction

In this tutorial, we will guide you through the process of creating a Task Manager API using Django, a powerful Python web framework, and MySQL as the database. This step-by-step tutorial includes setting up the development environment, configuring the MySQL database, defining API endpoints, and testing the API.

Step 1: Set Up the Development Environment

1.1 Create a Project Directory and Virtual Environment

To begin, create a project directory and set up a virtual environment to isolate your project dependencies.

mkdir task_manager_project
cd task_manager_project
python -m venv venv
source venv/bin/activate  # On Windows, use "venv\Scripts\activate"
Enter fullscreen mode Exit fullscreen mode

1.2 Install Django and Django Rest Framework

Next, install Django and Django Rest Framework using pip.

pip install django djangorestframework
Enter fullscreen mode Exit fullscreen mode

1.3 Create a Django Project and App

Create a new Django project named task_manager and a separate app named tasks within the project.

django-admin startproject task_manager
cd task_manager
python manage.py startapp tasks
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up the MySQL Database

2.1 Install MySQL

You will need to install MySQL server and the MySQL client for Python. You can download MySQL from the official website (https://dev.mysql.com/downloads/installer/) and follow the installation instructions.

2.2 Configure the MySQL Database

Open the project's settings (settings.py) and configure the database settings to use MySQL. Replace 'your_username' and 'your_password' with your MySQL credentials.

# task_manager/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'task_manager_db',
        'USER': 'your_username',
        'PASSWORD': 'your_password',
        'HOST': 'localhost',  # MySQL host
        'PORT': '3306',       # MySQL port
    }
}
Enter fullscreen mode Exit fullscreen mode

2.3 Apply Migrations and Create the Database

Apply initial database migrations to create the necessary database tables.

python manage.py makemigrations tasks
python manage.py migrate tasks
Enter fullscreen mode Exit fullscreen mode

Step 3: Create Models for Task Management

3.1 Define the Task Model

In your app's models.py file (tasks/models.py), define the Task model with fields for task details and status.

# tasks/models.py

from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title
Enter fullscreen mode Exit fullscreen mode

3.2 Create Migrations and Apply Them

Create migrations and apply them to update the database with the new Task model.

python manage.py makemigrations tasks
python manage.py migrate tasks
Enter fullscreen mode Exit fullscreen mode

Step 4: Create API Endpoints

4.1 Create a Serializers Class

In your app, create a Serializers class to define how the Task model should be serialized.

# tasks/serializers.py

from rest_framework import serializers
from .models import Task

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = '__all__'
Enter fullscreen mode Exit fullscreen mode

4.2 Create a Views Class

Create a Views class in your app to define the API views using Django Rest Framework.

# tasks/views.py

from rest_framework import viewsets
from .models import Task
from .serializers import TaskSerializer

class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
Enter fullscreen mode Exit fullscreen mode

4.3 Configure the API URLs

Configure the API URLs by creating a urls.py file in your app to define the routing.

# tasks/urls.py

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import TaskViewSet

router = DefaultRouter()
router.register(r'tasks', TaskViewSet)

urlpatterns = [
    path('', include(router.urls)),
]
Enter fullscreen mode Exit fullscreen mode

4.4 Include the App's URL Configuration

Include the app's URL configuration in the project's urls.py.

# task_manager/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('tasks.urls')),  # Include the app's URLs
]
Enter fullscreen mode Exit fullscreen mode

Step 5: Run the Development Server

  1. Start the development server.
python manage.py runserver
Enter fullscreen mode Exit fullscreen mode
  1. Visit http://localhost:8000/admin/ to access the Django admin panel and create tasks.

  2. Access the Task Manager API at the following endpoints for CRUD operations on tasks:

  • List all tasks: http://localhost:8000/api/tasks/
  • Create a task: Send a POST request to http://localhost:8000/api/tasks/
  • Retrieve a task: http://localhost:8000/api/tasks/<task_id>/
  • Update a task: Send a PUT or PATCH request to http://localhost:8000/api/tasks/<task_id>/
  • Delete a task: Send a DELETE request to http://localhost:8000/api/tasks/<task_id>/

You have now created a Task Manager API using Django and MySQL. Students can extend this project by adding more features like user authentication, additional fields in the Task model, and more advanced API endpoints. Enjoy developing your task management application!

💖 💪 🙅 🚩
msnmongare
Sospeter Mong'are

Posted on October 19, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Django dev
webdev Django dev

May 10, 2024

Django + Tailwind CSS
webdev Django + Tailwind CSS

May 19, 2023