0% found this document useful (0 votes)
4 views6 pages

Django REST API Guide

This document is a step-by-step guide for setting up a RESTful Blog API using Django and Django REST Framework, covering both SQLite and MySQL databases. It includes prerequisites, detailed instructions for creating the project, defining models, serializers, views, and configuring URLs, as well as switching to a MySQL database in Part 2. Additionally, it provides common issues and troubleshooting tips for users during the setup process.

Uploaded by

yah boi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views6 pages

Django REST API Guide

This document is a step-by-step guide for setting up a RESTful Blog API using Django and Django REST Framework, covering both SQLite and MySQL databases. It includes prerequisites, detailed instructions for creating the project, defining models, serializers, views, and configuring URLs, as well as switching to a MySQL database in Part 2. Additionally, it provides common issues and troubleshooting tips for users during the setup process.

Uploaded by

yah boi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Django REST API

Step-by-Step Setup Guide


Blog API Project with SQLite & MySQL

Overview
This guide walks you through building a RESTful Blog API using Django and Django REST
Framework. The project exposes endpoints for creating, reading, updating, and deleting blog
posts. Part 1 uses the built-in SQLite database. Part 2 shows how to switch to MySQL.

Prerequisites
• Python 3.8 or newer installed
• PyCharm IDE (or any Python IDE / text editor)
• pip package manager
• MySQL Server (only required for Part 2)

Part 1 — Build the Django REST API

Step 1: Create the Project Folder


Create a new folder called aidemo and open it in PyCharm.
mkdir aidemo
cd aidemo

Step 2: Create [Link]


Inside the aidemo folder, create a file named [Link] with the following content:
Django
djangorestframework
environs

Step 3: Install Dependencies


Open a terminal in PyCharm (or your OS terminal) inside the aidemo folder and run:
pip install -r [Link]
💡 Note: This installs Django, the REST framework, and the environs library for environment
variable management.

Step 4: Create the Django Project


Create a new Django project called blogapi:
python -m django startproject blogapi
This creates a blogapi folder containing [Link], [Link], [Link], [Link], and [Link].

Step 5: Navigate into the Project Directory


cd blogapi
Verify that [Link] is present in this directory before continuing.

Step 6: Create the api App


python [Link] startapp api
Django will create an api folder with these files automatically: [Link], [Link], [Link],
[Link], migrations/. You will need to manually create two additional files: [Link] and
[Link] inside the api folder.

Step 7: Register the App in [Link]


Open blogapi/[Link] and find the INSTALLED_APPS list. Add the two entries shown below:
INSTALLED_APPS = [
...
"api",
"rest_framework",
]

Step 8: Define the BlogPost Model


Open api/[Link] and replace its contents with the following:
from [Link] import models

class BlogPost([Link]):
title = [Link](max_length=100)
content = [Link]()
published_date = [Link](auto_now_add=True)

def __str__(self):
return [Link]
💡 Note: auto_now_add=True automatically sets the published_date to the current timestamp
when a post is created.
Step 9: Create the Serializer
Create a new file api/[Link] and add the following code:
from rest_framework import serializers
from .models import BlogPost

class BlogPostSerializer([Link]):
class Meta:
model = BlogPost
fields = ["id", "title", "content", "published_date"]
💡 Note: The serializer converts BlogPost model instances to and from JSON for the API.

Step 10: Create the Views


Open api/[Link] and replace its contents with the following:
from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import BlogPost
from .serializers import BlogPostSerializer

class BlogPostListCreate([Link]):
queryset = [Link]()
serializer_class = BlogPostSerializer

class BlogPostRetrieveUpdateDestroy([Link]):
queryset = [Link]()
serializer_class = BlogPostSerializer
lookup_field = 'pk'

class BlogPostListCreate(APIView):
def get(self, request, format=None):
title = request.query_params.get("title", "")
if title:
blog_posts =
[Link](title__icontains=title)
else:
blog_posts = [Link]()
serializer_class = BlogPostSerializer(blog_posts, many=True)
return Response(serializer_class.data,
status=status.HTTP_200_OK)

Step 11: Update the Main URL Configuration


Open blogapi/[Link]. Add an import for include and replace or update urlpatterns as follows:
from [Link] import admin
from [Link] import path, include

urlpatterns = [
path('admin/', [Link]),
path('', include('[Link]')),
]
Step 12: Create the App-Level URL Configuration
Create a new file api/[Link] with the following content:
from [Link] import path
from . import views

urlpatterns = [
path('blogposts/', [Link].as_view(), name='blogpost-
view-create'),
path('blogposts/<int:pk>',
[Link].as_view(), name='update'),
]

Step 13: Run Database Migrations


First, create the migration files based on your models:
python [Link] makemigrations
Then apply the migrations to create the database tables:
python [Link] migrate

Step 14: Start the Development Server


python [Link] runserver
The server will start at [Link] Opening that URL directly will show an error
because no view is mapped to /. Navigate to the correct endpoint instead:
[Link]
💡 Note: You should see the Django REST Framework browsable API interface listing all blog
posts (empty to start).

API Endpoint Reference

Endpoint Method(s) Description


/blogposts/ GET List all blog posts
/blogposts/ POST Create a new blog post
/blogposts/<pk> GET Retrieve a specific blog post by ID
/blogposts/<pk> PUT / PATCH Update a specific blog post
/blogposts/<pk> DELETE Delete a specific blog post
Part 2 — Switch to MySQL Database

By default, Django uses SQLite, which stores data in a local file (db.sqlite3). For production or
multi-user environments, MySQL is a better choice.

Prerequisites for MySQL


• MySQL Server installed and running on localhost, port 3306
• A database named apidb created in MySQL
• The mysqlclient Python package installed

Install the MySQL Python Driver


pip install mysqlclient
💡 Note: On some systems you may also need: pip install PyMySQL

Create the Database in MySQL


Log in to MySQL and create the database before running migrations:
mysql -u root -p
CREATE DATABASE apidb;
EXIT;

Update DATABASES in [Link]


Open blogapi/[Link]. Find the DATABASES setting (which currently points to SQLite) and
replace it with the MySQL configuration:
DATABASES = {
'default': {
'ENGINE': '[Link]',
'NAME': 'apidb',
'USER': 'root',
'PASSWORD': 'your_mysql_password',
'HOST': 'localhost',
'PORT': '3306',
}
}
💡 Note: Replace 'your_mysql_password' with your actual MySQL root password. For security,
consider using environment variables via the environs library instead of hardcoding credentials.
Re-run Migrations
After updating the database settings, run migrations again to create the tables in MySQL:
python [Link] makemigrations
python [Link] migrate

Restart and Test


python [Link] runserver
Navigate to [Link] again. The API now reads from and writes to your
MySQL database.

Common Issues & Troubleshooting

Issue Solution
[Link] shows an error Navigate to /blogposts/ — no view is mapped to the root URL
ModuleNotFoundError: Run: pip install djangorestframework
rest_framework
No module named 'MySQLdb' Run: pip install mysqlclient
[Link] Ensure MySQL is running and apidb database exists
makemigrations shows No changes Ensure 'api' is in INSTALLED_APPS in [Link]

You might also like