cursor
en
Intermediate
Best Practices for Django RESTful API Development
This rule outlines essential principles and guidelines for developing scalable RESTful APIs using Django, focusing on code quality, project structure, and performance optimization.
Installation Instructions
Save this file in .cursor/rules directory
Rule Content
# Core Principles
## Django-First Approach
Utilize Django's built-in features and tools to maximize its capabilities.
## Code Quality
Prioritize readability and maintainability; adhere to Django's coding style guide (PEP 8).
## Naming Conventions
Use descriptive variable and function names, following lowercase_with_underscores for functions and variables.
## Modular Architecture
Structure projects in a modular way using Django apps to enhance reusability and separation of concerns.
## Performance Awareness
Consider scalability and performance in design decisions.
# Project Structure
## Application Structure
```
app_name/
├── migrations/ # Database migration files
├── admin.py # Django admin configuration
├── apps.py # App configuration
├── models.py # Database models
├── managers.py # Custom model managers
├── signals.py # Django signals
├── tasks.py # Celery tasks (if applicable)
└── __init__.py # Package initialization
```
## API Structure
```
api/
└── v1/
├── app_name/
│ ├── urls.py # URL routing
│ ├── serializers.py # Data serialization
│ ├── views.py # API views
│ ├── permissions.py # Custom permissions
│ ├── filters.py # Custom filters
│ └── validators.py # Custom validators
└── urls.py # Main API URL configuration
```
## Core Structure
```
core/
├── responses.py # Unified response structures
├── pagination.py # Custom pagination classes
├── permissions.py # Base permission classes
├── exceptions.py # Custom exception handlers
├── middleware.py # Custom middleware
├── logging.py # Structured logging utilities
└── validators.py # Reusable validators
```
## Configuration Structure
```
config/
├── settings/
│ ├── base.py # Base settings
│ ├── development.py # Development settings
│ ├── staging.py # Staging settings
│ └── production.py # Production settings
├── urls.py # Main URL configuration
└── wsgi.py # WSGI configuration
```
# Development Guidelines
## Views and API Design
- Use Class-Based Views (CBVs) with Django REST Framework's APIViews.
- Strictly follow RESTful principles with correct HTTP methods and status codes.
- Keep views focused on request handling; business logic should reside in models, managers, and services.
- Maintain a consistent response format for success and error cases.
## Models and Database
- Utilize Django's ORM for database interactions; limit raw SQL usage.
- Embed business logic within models and custom managers.
- Optimize queries with select_related and prefetch_related.
- Implement proper indexing for frequently queried fields.
- Use transaction.atomic() for critical operations requiring data consistency.
## Serializers and Validation
- Employ Django REST Framework serializers for data validation and serialization.
- Create custom validators for complex business rules.
- Implement field-level validation for input sanitization.
- Handle nested relationships with appropriate serializers.
## Authentication and Permissions
- Use djangorestframework_simplejwt for JWT token-based authentication.
- Create granular permission classes for different user roles.
- Follow security best practices, including CSRF protection and CORS configuration.
## URL Configuration
- Define clean URL patterns using urlpatterns, mapping paths to views.
- Organize URLs modularly using include().
- Implement API versioning, preferably via URL-based strategies.
# Performance and Scalability
## Query Optimization
- Prevent the N+1 problem by using select_related and prefetch_related appropriately.
- Monitor query counts and execution times during development.
- Implement database connection pooling for high-traffic applications.
- Utilize Django's cache framework with Redis/Memcached for frequently accessed data.
## Response Optimization
- Standardize pagination across all list endpoints.
- Allow clients to specify required fields to reduce payload size.
- Enable response compression for large payloads.
# Error Handling and Logging
## Unified Error Responses
```json
{
"success": false,
"message": "Error description",
"errors": {
"field_name": ["Specific error details"]
},
"error_code": "SPECIFIC_ERROR_CODE"
}
```
## Exception Handling
- Implement a global exception handler for consistent error responses.
- Use Django signals to decouple error handling from model activities.
- Apply appropriate HTTP status codes (400, 401, 403, 404, 422, 500, etc.).
## Logging Strategy
- Implement structured logging for API monitoring and debugging.
- Log API calls, including execution time, user info, and response status.
- Monitor slow queries and performance bottlenecks.Tags
Django
RESTful API
Python
Code Quality
Performance
Modular Architecture
Score: 0Downloads: 0Created: 1/11/2026