How to Create an API with Django: A Complete Guide
Django REST Framework (DRF) is the go-to toolkit for building APIs in Django. In this tutorial, you’ll create a fully functional REST API for a simple blog model.
Start by setting up your environment: install Django and DRF with pip install django djangorestframework. Create a project (django-admin startproject myproject) and an app (python manage.py startapp blog). Add rest_framework and blog to INSTALLED_APPS.
1. Define Your Model
Open blog/models.py and define a model:
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
Run python manage.py makemigrations and migrate to create the database table.
2. Create a Serializer
Serializers convert model instances into JSON. Create blog/serializers.py:
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = '__all__'
3. Build ViewSets and URLs
In blog/views.py, use a ModelViewSet for automatic CRUD operations:
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
Finally, register a router in your main urls.py:
router = DefaultRouter()
router.register('posts', PostViewSet)
urlpatterns += router.urls
4. Test Your API
Run python manage.py runserver and visit /posts/. Use curl or Postman to test POST, GET, PUT, and DELETE requests.
Conclusion
You now have a complete REST API built with Django REST Framework. DRF handles serialization, routing, and permissions automatically, letting you focus on your application logic and data.