0
0
Djangoframework~5 mins

DRF installation and setup in Django

Choose your learning style9 modes available
Introduction

DRF helps you build web APIs easily with Django. It makes sharing data between your app and others simple.

You want to create a web API for your Django app.
You need to send data from your server to a mobile app.
You want to allow other developers to use your app's data.
You want to build a backend for a single-page app or frontend framework.
You want to handle JSON data easily in Django.
Syntax
Django
pip install djangorestframework

# Then add 'rest_framework' to INSTALLED_APPS in settings.py
INSTALLED_APPS = [
    ...
    'rest_framework',
]
Use pip to install the package from the command line.
Adding 'rest_framework' to INSTALLED_APPS tells Django to use DRF features.
Examples
Installs the Django REST Framework package.
Django
pip install djangorestframework
Adds DRF to your Django project settings.
Django
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'rest_framework',
]
Sample Program

This example shows how to install DRF, add it to your project, create a simple API view that returns a message, and connect it to a URL.

Django
# 1. Install DRF
# Run in terminal:
# pip install djangorestframework

# 2. Add to settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'rest_framework',
]

# 3. Create a simple API view in views.py
from rest_framework.views import APIView
from rest_framework.response import Response

class HelloWorld(APIView):
    def get(self, request):
        return Response({"message": "Hello, world!"})

# 4. Add URL in urls.py
from django.urls import path
from .views import HelloWorld

urlpatterns = [
    path('hello/', HelloWorld.as_view()),
]

# Now, running the server and visiting /hello/ returns JSON with message.
OutputSuccess
Important Notes

Make sure to restart your Django server after installing and updating settings.

You can test your API by visiting the URL in a browser or using tools like curl or Postman.

Summary

Install DRF using pip and add it to your Django settings.

Create API views by subclassing DRF classes like APIView.

Connect views to URLs to make your API accessible.