DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • REST Assured: CRUD Framework for API Testing
  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Model-Driven Development and Testing
  • Instant APIs With Copilot and API Logic Server

Trending

  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Dropwizard vs. Micronaut: Unpacking the Best Framework for Microservices
  • Building Resilient Networks: Limiting the Risk and Scope of Cyber Attacks
  • Ensuring Configuration Consistency Across Global Data Centers
  1. DZone
  2. Coding
  3. Frameworks
  4. Create a Simple API Using Django REST Framework in Python

Create a Simple API Using Django REST Framework in Python

Read this article in order to learn more about how to create a simple API using Django REST framework in Python.

By 
Vinay R user avatar
Vinay R
DZone Core CORE ·
Jun. 02, 18 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
70.6K Views

Join the DZone community and get the full member experience.

Join For Free

Video

Steps to Create a Simple Django REST API Project

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.

Prerequisites

Install either Python or the Anacondas distribution of Python.

Install the Django and Django REST frameworks with below commands:

  • pip install django
  • pip install djangorestframework

For the Anacondas Python distribution, use the below commands:

  • conda install django
  • conda install -c conda-forge djangorestframework

Step 1: 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

Step2: 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:

Step 3: Open the settings.py file and add the below lines of code in the INSTALLED_APPS section:
'rest_framework',
 'MyApp',
Step4: 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)


The IdealWeight(heightdate) is the method that gets executed when API call is made. It has a simple logic to calculate weight(=height*10). The line return JsonRespone(…) will send the response back.

Step5: Open urls.py file and add the below lines of code:
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://<server ip>/idealweight/

Step6: We can start the api with below commands in command prompt:

python manage.py runserver

Finally, we can test the API using POSTMAN.

API REST Web Protocols Django (web framework) Python (language) Framework

Opinions expressed by DZone contributors are their own.

Related

  • REST Assured: CRUD Framework for API Testing
  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Model-Driven Development and Testing
  • Instant APIs With Copilot and API Logic Server

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!