Django — REST API
REST Principles
| Principle | Description |
|---|---|
| Stateless | No client context stored |
| Client-Server | Separate concerns |
| Cacheable | Responses can be cached |
| Uniform Interface | Consistent API |
HTTP Methods
| Method | Action | Status |
|---|---|---|
| GET | Read | 200 |
| POST | Create | 201 |
| PUT | Update | 200 |
| PATCH | Partial update | 200 |
| DELETE | Delete | 204 |
API Endpoints
GET /api/posts/ # List all
POST /api/posts/ # Create one
GET /api/posts/{id}/ # Get one
PUT /api/posts/{id}/ # Update one
DELETE /api/posts/{id}/ # Delete one
Pagination
# settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
Filtering
from rest_framework import filters
class PostList(generics.ListAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
filter_backends = [filters.SearchFilter, filters.OrderingFilter]
search_fields = ['title', 'content']
ordering_fields = ['created_at']
Mini Practice
- Design REST endpoints
- Implement CRUD operations
- Add pagination
- Add search and filtering
Up Next
Continue with Serializers — data serialization.
Related Topics
Frequently Asked Questions about REST API
What is REST API in Django?
REST API is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn REST API?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn REST API.
Why is REST API important in Django?
REST API is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.