Creating a Task Manager API with Django and MySQL
Tags: webdev, beginners, programming, django
Published: 2023-10-19 21:12:00


## 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.

```bash
mkdir task_manager_project
cd task_manager_project
python -m venv venv
source venv/bin/activate  # On Windows, use "venv\Scripts\activate"
```

### 1.2 Install Django and Django Rest Framework

Next, install Django and Django Rest Framework using `pip`.

```bash
pip install django djangorestframework
```

### 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.

```bash
django-admin startproject task_manager
cd task_manager
python manage.py startapp tasks
```

## 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.

```python
# 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
    }
}
```

### 2.3 Apply Migrations and Create the Database

Apply initial database migrations to create the necessary database tables.

```bash
python manage.py makemigrations tasks
python manage.py migrate tasks
```

## 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.

```python
# 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
```

### 3.2 Create Migrations and Apply Them

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

```bash
python manage.py makemigrations tasks
python manage.py migrate tasks
```

## 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.

```python
# tasks/serializers.py

from rest_framework import serializers
from .models import Task

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = '__all__'
```

### 4.2 Create a Views Class

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

```python
# 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
```

### 4.3 Configure the API URLs

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

```python
# 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)),
]
```

### 4.4 Include the App's URL Configuration

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

```python
# 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
]
```

## Step 5: Run the Development Server

1. Start the development server.

```bash
python manage.py runserver
```

2. Visit `http://localhost:8000/admin/` to access the Django admin panel and create tasks.

3. 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!