Django Rest Framework
UpDRF is a library which allows you to build APIs in your Django project.
How to install Django
Run,pip install Django
Starting a new project
Django-admin startproject drf
Installing Django rest Framework
Pip install Django Rest Framework
Create a new file in your project and name it views.py
In the views.py import render like this:
From Django shortcuts import render
The rest Framework provides us with an API view class or function.
This will help us access alot of APis available in the Djngo rest Framework.
Start:
From rest_framework.views import APIViews
In order to get a response from users who send request to our APIs we need to import the following
From rest_framework.response import Response
Now let us go to the urls.py if the project and import the class based views.On configuring the urls,make sure it is marked as_viee because the view was a class based view.
Before we run the project,let us make some settings in the settings section.
We need to add Django rest Framework in the installed apps,in the settings.
We can therefore come to our command prompt and run, python manage.py runserver.
Django Rest Framework serializers.
Serializers is a structure representation tht represents a data,we want to return in a JSON format.
We can use serializers to like transform our Django models into JSON.Lets first create a new app into our Django project then we will dive
deeper into serializers.
Python
manage
.py
startapp
drfapp
Let's now go to our models and create a model that we can play around with.
Let's talk more of serializers
The serializers is a model form for model,so you can submit in Django,or update.
Let's dive into practicals
We have to create a new app and name it serializers.py.This is the file that we will use to configure our new model that we are going to use.
In the models.py let us create a new model and name it let's say Student.
Class student(models.model)
Let's add fields:
Name =models.Charfield(max_length=100)
Age=models.IntegerField()
Description=models.TextField()
def __str__(self):
Return self.name
We know very well that in Django before we do anything we have to make migrations in the CLI.
Let's now go back into the serializers.py,we need to import the serializers from the rest Framework and also the post models from models.py file.Later we can create a serializer for our post model by specifying in some fields.
Let's start with:
From rest_framework import serializers
From .models import Student
Class StudentSerializer(serializers.ModelSerializer):
Class Meta:
Model=Student
Fields= (
'nams','age',
)