In this video, you'll learn how to install and configure DRF in a Django project with ease. You'll have the option to use pip or pipenv to manage the dependencies.
- Start by opening the terminal and navigating to your project directory.
- If using pipenv, run the following commands:
pipenv install django
pipenv shell
pipenv install djangorestframework
- If using pip, run the following command:
pip or pip3 install djangorestframework
In the terminal, run the following commands:
django-admin startproject BookList .
python manage.py startapp BookListAPI
- Open the
settings.py
file in the project directory and find theINSTALLED_APPS
section. - Add
rest_framework
andBookListAPI
to the end of the list.
- In the
views.py
file of theBookListAPI
app, add the following code:
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
# Create your views here.
@api_view()
def books(request):
return Response("list of books", status=status.HTTP_200_OK)
- Create a new file called
urls.py
in theBookListAPI
directory and add the following code:
from django.urls import path
from . import views
urlpatterns = [
path("books/", views.books),
]
- In the project's main
urls.py
file, add the following line to link the newly created books endpoint:
from django.urls import include
urlpatterns = [
path('api/', include('BookListAPI.urls')),
]
- Run the migrate command in the terminal:
python3 manage.py migrate
- Start the web server using the following command:
python3 manage.py runserver
-
Access the books endpoint by making an HTTP GET request to
http://127.0.0.1:8000/api/books
using a tool like Insomnia. -
If you want to accept other HTTP methods like POST, PUT, or DELETE, you need to define them in the API view decorator. For example, to accept POST requests, add
['POST']
in the@api_view
decorator.