Creating Restful Apis with Python and Django Rest Framework

Creating RESTful APIs is essential for enabling communication between different software systems. Python, combined with Django Rest Framework (DRF), provides a powerful and flexible way to develop these APIs efficiently. This article covers the basic steps to create a RESTful API using Python and DRF.

Setting Up the Environment

Begin by installing Python and Django. Use pip to install Django Rest Framework:

Commands:

“`bash pip install django pip install djangorestframework “`

Create a new Django project and app:

“`bash django-admin startproject myproject cd myproject python manage.py startapp api “`

Defining the Data Model

In the app directory, define a model in models.py:

Example:

“`python from django.db import models class Item(models.Model): name = models.CharField(max_length=100) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) “`

Creating Serializers

Serializers convert model instances into JSON format. Create a serializers.py file in the app directory:

Example:

“`python from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ‘__all__’ “`

Creating Views and URLs

Define API views in views.py:

Example:

“`python from rest_framework import generics from .models import Item from .serializers import ItemSerializer class ItemList(generics.ListCreateAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer class ItemDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer “`

Configure URLs in urls.py:

Example:

“`python from django.urls import path from .views import ItemList, ItemDetail urlpatterns = [ path(‘items/’, ItemList.as_view(), name=’item-list’), path(‘items//’, ItemDetail.as_view(), name=’item-detail’), ] “`

Running the API

Apply migrations and run the development server:

Commands:

“`bash python manage.py makemigrations python manage.py migrate python manage.py runserver “`

Access the API at http://127.0.0.1:8000/items/ to view, create, update, or delete items.