Share and Learn To Write Code!

Programming articles, which help you to build your application. If something you are stuck to code and complete the program, just find here your question-related articles.

Share with   

Write rest api using python django rest framework using json response method

We can write rest api using python django rest framework using json response method. How to send Json data with JsonResponse method.
python   django   django rest framework   django rest api   rest api  

Django Json Response


We are going to see how we can write api to send Json data using JsonResponse Method in django rest framework.


Django


Django is a high-level Python web framework.

It energizes fast advancement and spotless.

Django's essential objective is to facilitate the production of complex, database-driven websites.

Django is kept up by the Django Software Foundation.



Json Data


JSON (JavaScript Object Notation) is a lightweight information trade design. 

The official Internet media type for JSON is application/json.

The JSON filename extension is .json.

It is simple for humans to peruse and compose and for machines to parse and create.


Django JsonResponse


JsonResponse is part of HttpResponse which helps to create JSON Response. Its content type is set to application/json.


Example


In the following example we are create dajngo project for sending api which is having JSON object response.


Prerequisite

  1. Install Python
  2. Install Django click for how to install Django and python.


Setup


Create Python Virtual Environment

mkvirtualenv json_response_demo

Install Django

pip install django

Create Django Project

django-admin startproject EmployeeData

Create Django App

django-admin startapp api

Register api app in django settings install apps.

# EmployeeData > EmployeeData > settings.py
INSTALLED_APPS = [
	    'django.contrib.admin',
	    'django.contrib.auth',
	    'django.contrib.contenttypes',
	    'django.contrib.sessions',
	    'django.contrib.messages',
	    'django.contrib.staticfiles',
	    'api',
	]

Write Send Employee Data using json view

# EmployeeData > api > views.py

from django.http import JsonResponse

def send_json(request):

    data = [{'name': 'Bhushan', 'email': 'bhushan@example.org'},
            {'name': 'Amit', 'email': 'amit@example.org'}]

    return JsonResponse(data, safe=False)

Add route into urls.py file

# EmployeeData > EmployeeData > urls.py

from django.contrib import admin
from django.urls import path
from .views import send_json

urlpatterns = [
    path('admin/', admin.site.urls),
    path('sendjson/', send_json, name='send_json'),
]

Now migrate the app and run server.

To test this API into postman. If you dont know how postman work please check this article.


0replies
Leave a reply
46
Registerd Users
88
Total Subscribers
59
Total Articles
42108
Total Views