This repository contains a basic Django REST Framework (DRF) practice project with CRUD operations on the User model.
Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs in Django. It provides features like serialization, authentication, permissions, and viewsets to make API development easier and more efficient.
Follow these basic commands to set up a DRF project:
-
Install Django and DRF:
pip install django djangorestframework
-
Create a new Django project:
django-admin startproject myproject cd myproject
-
Create a Django app:
python manage.py startapp myapp
-
Add
rest_framework
toINSTALLED_APPS
insettings.py
-
Apply migrations:
python manage.py migrate
-
Run the server:
python manage.py runserver
Models define the database schema using Django's ORM. Each model is a Python class that subclasses models.Model
and defines fields that map to database columns.
Serializers allow complex data types such as Django models to be converted into JSON and vice versa. DRF provides ModelSerializer
to automatically generate fields based on a model.
Views handle the logic for API requests. DRF provides function-based views (FBVs) and class-based views (CBVs), including generic views for common operations like list, create, retrieve, update, and delete.
URLs route API requests to the appropriate views. DRF uses Django's path()
and re_path()
functions along with DefaultRouter
for viewsets.
DRF supports various authentication classes like TokenAuthentication
, SessionAuthentication
, and JWTAuthentication
. Permissions restrict access to API endpoints based on user roles and conditions.
SimpleJWT is a library used for implementing JSON Web Token (JWT) authentication in DRF. It provides access
and refresh
tokens for secure authentication.
Install SimpleJWT:
pip install djangorestframework-simplejwt
Configure JWT Authentication in settings.py
:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
DRF provides built-in pagination classes like PageNumberPagination
and LimitOffsetPagination
to manage large querysets efficiently.
DRF supports filtering and ordering of querysets using django-filter
and ordering_fields
to allow dynamic sorting.
Follow these steps to set up the project:
-
Create a virtual environment and activate it:
python -m venv venv source venv/bin/activate # On Windows use `venv\Scripts\activate`
-
Install dependencies:
pip install -r requirements.txt
-
Apply migrations:
python manage.py migrate
-
Run the server:
python manage.py runserver
Method | Endpoint | Description |
---|---|---|
GET | /api/users/ |
Get all users |
GET | /api/user/ |
Perform CRUD on a single user |
POST | /api/register/ |
Register a new user |
POST | /api/login/ |
Login user and get tokens |
POST | /api/token/refresh/ |
Refresh the access token |
This project is open-source and available for learning purposes.