In this article, we’ll talk about building APIs and how to do it, step by step. I believe this is going to be useful for all beginner Django developers, as REST APIs are used in every application or piece of software to connect the backend and frontend parts. If you master this, you can build all kinds of products.
In this Django API tutorial, we will create a simple API, which will accept the height (in feet) of a person and returns the ideal weight (in kgs) for that person to be.
Install either Python or the Anacondas distribution of Python.
Install the Django and Django REST frameworks with below commands:
For the Anacondas Python distribution, use the below commands:
Navigate to any folder you want in order to create the django project, open the command prompt there and enter the following command:
django-admin startproject SampleProject
Navigate to the project folder and create a web app using the below command:
python manage.py startapp MyApp
The project folder will look something like this:
Open the settings.py file and add the below lines of code in the INSTALLED_APPS section:
'rest_framework',
'MyApp',
Open views.py file inside MyApp folder and add the below lines of code:
from django.shortcuts import render
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.http import JsonResponse
from django.core import serializers
from django.conf import settings
import json
# Create your views here.
@api_view(["POST"])
def IdealWeight(heightdata):
try:
height=json.loads(heightdata.body)
weight=str(height*10)
return JsonResponse("Ideal weight should be:"+weight+" kg",safe=False)
except ValueError as e:
return Response(e.args[0],status.HTTP_400_BAD_REQUEST)
Open urls.py file and add the below lines of code:</section>
from django.conf.urls import url
from django.contrib import admin
from MyApp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^idealweight/',views.IdealWeight)
]
The line url(r^idealweight/,views.IdealWeight) basically tells us that the IdealWeight method will be called using the url http:///idealweight/
We can start the api with below commands in command prompt:
python manage.py runserver
Finally, we can test the API using POSTMAN.
Thanks for reading .
#python #Django