📅  最后修改于: 2023-12-03 15:00:26.649000             🧑  作者: Mango
Django REST Framework is a powerful and flexible toolkit for building Web APIs. It is built on top of Django, which means that it follows the same best practices and conventions as Django itself.
Here are some key features of Django REST Framework:
To get started with Django REST Framework, you need to install it first. You can install Django REST Framework through pip:
pip install djangorestframework
Next, add 'rest_framework' to your INSTALLED_APPS setting in settings.py. You should also include the default authentication and permission classes, or customize them to suit your needs:
INSTALLED_APPS = [
...
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
Once installed, you can start building your API using the Django REST Framework. Define your views using viewsets and serializers, and add them to your urls.py file:
from rest_framework import viewsets
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
urlpatterns = [
path('api/', BookViewSet.as_view({'get': 'list', 'post': 'create'})),
path('api/<int:pk>/', BookViewSet.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]
That's it! You now have a fully functional API that supports CRUD operations for your Book model.
Django REST Framework is a powerful and flexible toolkit for building Web APIs with Python. It provides a wide range of features and uses the same conventions as Django, making it easy to integrate into existing Django projects. Whether you need authentication, permissions, serialization, or any other API-related functionality, Django REST Framework has you covered.