This is a beginner-friendly Django REST Framework (DRF) project that demonstrates how to create a complete API with full CRUD (Create, Read, Update, Delete) operations. The project includes a User model and comprehensive API endpoints for managing user data.
By studying this project, beginners will learn:
- How Django models represent database tables
- How serializers convert between Python objects and JSON
- How views handle different HTTP methods (GET, POST, PUT, DELETE)
- How URL routing works in Django
- How to use Django's admin interface for data management
- How to build a complete REST API from scratch
drfdemo/
├── manage.py # Django's command-line utility
├── db.sqlite3 # SQLite database file
├── README.md # This documentation file
├── drfdemo/ # Main project directory
│ ├── __init__.py # Makes this a Python package
│ ├── settings.py # Project configuration and settings
│ ├── urls.py # Main URL routing configuration
│ ├── wsgi.py # Web Server Gateway Interface
│ └── asgi.py # Asynchronous Server Gateway Interface
└── api/ # Your custom API application
├── __init__.py # Makes this a Python package
├── models.py # Database models (User model definition)
├── serializer.py # Data serialization (JSON conversion)
├── views.py # API logic (request handling)
├── urls.py # API-specific URL patterns
├── admin.py # Django admin configuration
├── apps.py # App configuration
├── tests.py # Test cases (for future testing)
└── migrations/ # Database migration files
├── __init__.py
└── 0001_initial.py
What it does: Defines the structure of your database tables using Python classes.
class User(models.Model):
name = models.CharField(max_length=100) # Text field for user's name
age = models.IntegerField() # Number field for user's ageKey Concepts:
- Each model class = one database table
- Each field = one column in the table
- Django automatically creates an
idfield as primary key __str__method controls how objects are displayed
What it does: Acts as a translator between Python objects and JSON data.
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'Key Concepts:
- Converts User objects → JSON (for API responses)
- Converts JSON → User objects (for API requests)
- Handles data validation automatically
ModelSerializercreates fields based on the model
What it does: Contains the logic for handling different HTTP requests.
-
Get All Users (
GET /api/users/)@api_view(['GET']) def get_users(request): users = User.objects.all() # Fetch all users serializer = UserSerializer(users, many=True) # Convert to JSON return Response(serializer.data) # Return as response
-
Create User (
POST /api/users/create)@api_view(['POST']) def create_user(request): serializer = UserSerializer(data=request.data) # Create serializer with request data if serializer.is_valid(): # Validate the data serializer.save() # Save to database return Response(serializer.data, status=201) # Return created user return Response(serializer.errors, status=400) # Return validation errors
-
User Detail Operations (
GET/PUT/DELETE /api/users/<id>/)@api_view(['GET', 'PUT', 'DELETE']) def user_detail(request, user_id): user = User.objects.get(id=user_id) # Find specific user if request.method == 'GET': # Read user data # Return user information elif request.method == 'PUT': # Update user data # Update and return modified user elif request.method == 'DELETE': # Delete user # Remove user from database
What it does: Maps URLs to view functions.
urlpatterns = [
path('admin/', admin.site.urls), # Django admin interface
path('api/', include('api.urls')), # Include API app URLs
]urlpatterns = [
path('users/', get_users, name='get_users'), # List all users
path('users/create/', create_user, name='create_user'), # Create new user
path('users/<int:user_id>/', user_detail, name='user_detail'), # Individual user operations
]What it does: Provides a web-based interface for managing data.
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
list_display = ['id', 'name', 'age'] # Columns to show in list view
search_fields = ['name'] # Enable search by name
list_filter = ['age'] # Add age filter sidebar- Python 3.x installed
- Basic understanding of Python
- Text editor or IDE (VS Code recommended)
-
Navigate to the project directory:
cd drfdemo -
Apply database migrations:
python manage.py makemigrations python manage.py migrate
-
Create a superuser (for admin access):
python manage.py createsuperuser
Follow the prompts to create an admin account.
-
Start the development server:
python manage.py runserver
-
Access the application:
- API:
http://127.0.0.1:8000/api/users/ - Admin:
http://127.0.0.1:8000/admin/
- API:
| Method | URL | Description | Example Request Body |
|---|---|---|---|
| GET | /api/users/ |
Get all users | None |
| POST | /api/users/create |
Create new user | {"name": "John Doe", "age": 30} |
| GET | /api/users/1/ |
Get user by ID | None |
| PUT | /api/users/1/ |
Update user | {"name": "Jane Doe", "age": 31} |
| DELETE | /api/users/1/ |
Delete user | None |
curl -X POST http://127.0.0.1:8000/api/users/create \
-H "Content-Type: application/json" \
-d '{"name": "Alice Johnson", "age": 28}'curl http://127.0.0.1:8000/api/users/curl -X PUT http://127.0.0.1:8000/api/users/1/ \
-H "Content-Type: application/json" \
-d '{"name": "Alice Smith", "age": 29}'curl -X DELETE http://127.0.0.1:8000/api/users/1/-
Study Models (
api/models.py)- Learn how Python classes represent database tables
- Understand different field types (
CharField,IntegerField) - Practice adding new fields to the User model
-
Explore Serializers (
api/serializer.py)- Understand the role of serializers in API development
- Learn about
ModelSerializervsSerializer - Practice customizing serializer fields
-
Master Views (
api/views.py)- Learn how
@api_viewdecorator works - Understand HTTP methods (GET, POST, PUT, DELETE)
- Practice error handling and validation
- Learn how
-
URL Routing (
urls.pyfiles)- Learn how Django routes URLs to views
- Understand URL parameters (
<int:user_id>) - Practice creating new URL patterns
- Admin Interface (
api/admin.py)- Learn how to register models
- Customize admin views
- Use admin for data management
- Testing Your API
- Use Django REST Framework's browsable API
- Test with tools like Postman or curl
- Write basic unit tests
-
Add Data Validation
- Add minimum/maximum age constraints
- Validate name format (no numbers, minimum length)
- Add email field with email validation
-
Improve Error Handling
- Add custom error messages
- Handle edge cases (empty requests, invalid IDs)
- Add logging for debugging
-
Add More Fields
class User(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() email = models.EmailField(unique=True) # New field created_at = models.DateTimeField(auto_now_add=True) # New field
-
Authentication & Permissions
- Add user authentication
- Implement API permissions
- Add user roles and access control
-
Advanced Querying
- Add search and filtering
- Implement pagination
- Add sorting options
-
API Documentation
- Add Swagger/OpenAPI documentation
- Create detailed API guides
- Add example requests/responses
- Update the model in
models.py - Create and apply migrations:
python manage.py makemigrations python manage.py migrate
- Update admin configuration if needed
- Add the model class to
models.py - Create a serializer for it in
serializer.py - Add views in
views.py - Configure URLs in
urls.py - Register in admin (optional)
- Use Django's browsable API:
http://127.0.0.1:8000/api/users/ - Test with curl commands (examples above)
- Use the Django admin interface
- Write unit tests in
tests.py
-
"No module named 'rest_framework'"
- Install Django REST Framework:
pip install djangorestframework
- Install Django REST Framework:
-
"Table doesn't exist" errors
- Run migrations:
python manage.py migrate
- Run migrations:
-
"Permission denied" in admin
- Create superuser:
python manage.py createsuperuser
- Create superuser:
-
Changes not appearing
- Restart the development server
- Clear browser cache
- Check for syntax errors in Python files
- Postman - API testing tool
- DB Browser for SQLite - Database viewer
- VS Code REST Client - VS Code extension for API testing
Q: What's the difference between Django and Django REST Framework? A: Django is a web framework for building websites, while Django REST Framework (DRF) is an extension that makes it easy to build Web APIs.
Q: Why use serializers instead of returning model objects directly? A: Serializers provide data validation, format conversion (Python ↔ JSON), and security by controlling which fields are exposed.
Q: What happens when I visit /api/users/?
A: Django matches the URL pattern, calls the get_users view function, which fetches users from the database and returns them as JSON.
Q: How do I add authentication to my API?
A: Django REST Framework provides multiple authentication options. Start with the built-in SessionAuthentication or TokenAuthentication.
Q: Can I use a different database than SQLite?
A: Yes! Django supports PostgreSQL, MySQL, SQLite, and Oracle. Change the database configuration in settings.py.