How to Create a basic API using Django Rest Framework?

How to Create a basic API using Django Rest Framework?

Django Rest Framework (DRF) is a powerful toolkit for building Web APIs in Django applications. Here's a basic walkthrough of creating an API using DRF:

1. Set up Django:

Firstly, make sure you've set up a Django project. If you haven't, you can set one up with:

django-admin startproject projectname 

2. Install Django Rest Framework:

You can install DRF using pip:

pip install djangorestframework 

3. Create an app:

Create a new app for your project:

python manage.py startapp appname 

4. Set up your model:

In appname/models.py, create a simple model. Here's an example:

from django.db import models class Item(models.Model): name = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.name 

5. Set up DRF:

In your project's settings.py, add 'rest_framework' and your app to the INSTALLED_APPS:

INSTALLED_APPS = [ ... 'rest_framework', 'appname', ] 

6. Create a Serializer:

Serializers in DRF allow complex data types, such as querysets and model instances, to be converted to Python data types that can be easily rendered into JSON.

In appname/serializers.py:

from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ['id', 'name', 'description'] 

7. Create a View:

In appname/views.py:

from rest_framework import generics from .models import Item from .serializers import ItemSerializer class ItemListCreate(generics.ListCreateAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer 

This view will allow you to list all items and create a new item.

8. Configure URLs:

In appname/urls.py:

from django.urls import path from .views import ItemListCreate urlpatterns = [ path('items/', ItemListCreate.as_view(), name='item-list-create'), ] 

Make sure to include this in the main urls.py of your project:

from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('appname.urls')), ] 

9. Run migrations:

Run the migrations to create the necessary database tables:

python manage.py makemigrations python manage.py migrate 

10. Start the development server:

python manage.py runserver 

Now, you should be able to visit http://localhost:8000/api/items/ to view the list of items and use tools like Postman or httpie to interact with your API, including listing items and adding new ones.

This is a very basic API. DRF offers many features like authentication, viewsets, routers, permissions, and more, which can be added as per requirements.


More Tags

zip nvarchar logfiles surfaceview treemap becomefirstresponder copy-paste jax-ws rack set-returning-functions

More Programming Guides

Other Guides

More Programming Examples