29 Jul 2024 by Ijeoma Jahsway
Category: Tools & Libraries
Frameworks: Python, Django
Read Time: 3 Minutes
Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs in Django. It makes it easy to build robust and scalable APIs by providing features such as serialization, authentication, and viewsets.
First, ensure you have Python and Django installed. Then, install Django REST Framework using pip:
pip install djangorestframework
Create a new Django project by running the following command:
django-admin startproject myapi
Navigate to your project directory and create a new app:
cd myapi
python manage.py startapp blog
Define your models in blog/models.py
. For example, you can create a simple Post
model:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
Serializers define the API representation. Create a serializer for your Post
model in blog/serializers.py
:
from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = '__all__'
Create API views to handle HTTP requests. Use Django REST Framework's viewsets to simplify this process. Define your views in blog/views.py
:
from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
Set up your API URLs in blog/urls.py
and include them in your project's urls.py
:
# blog/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import PostViewSet
router = DefaultRouter()
router.register(r'posts', PostViewSet)
urlpatterns = [
path('', include(router.urls)),
]
# myapi/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('blog.urls')),
]
Finally, run the development server to see your API in action:
python manage.py runserver
Visit http://127.0.0.1:8000/api/posts/
in your browser to interact with the API.
Congratulations! You've created a RESTful API using Django REST Framework. From here, you can explore more advanced features like authentication, permissions, and pagination.
Subscribe to our Telegram Channel to get exclusive content and be the first to know when new blog posts go live! 🎉