Django API

Django API : Creating APIs using Django

Creating APIs with django is very simple and easy process . We need to to create an different json or python format . Using Django  we can direct create APIs with Django database ( models ) .

What is API ?

API stands for Application Programming Interface . Basically the APIs are the set of rules or we can say code , which are written to provide the interaction between different applications . As the name suggest APIs are the interface between different applications .

In simple words we can say that APIs allows us to use the code , written by someone else . Let’s take an simple example , suppose you are going to develop an international shopping website . Here is large work that you have to do including getting product data , vendor data , upload data etc . Here also , you need a simple select option for all countries . Instead of adding all 196 countries manually one by one ,we need an interface which can automatically do this for us . This interface is actually an API . We can use APIs in  different applications including Web-apps , Mobile-apps etc, as shown in figure below:

 

django api

Mostly we create APIs in JSON or XML . If you want to learn more about JSON , then you can visit the link below:

JSON In Python

Creating Django API

Let’s creating an API from Django database (default is sql-lite3 ). I am creating simple API for adding multiple choice questions . Here is the complete process

Step 1

Create an django project using:

django-admin startproject projectName

Step 2

After that , inside project folder create an app using:

django-admin startapp appName

For example:

Django API
Django API

Step 3

Setup project , add app to project’s Settings.py file .For more details about creating project you can visit the link               below:

      Create Django Project

Step 4

Create an django model (which you want to create api) in app’s models.py file like this :

apiproject > api > models.py

from django.db import models
class addQuestion(models.Model):
    CHOICES = (
    ('a','A'),
    ('b','B'),
    ('c','C'),
    ('d','D')
    )

    question = models.CharField(max_length=500)
    option1 = models.CharField(max_length = 250)
    option2 = models.CharField(max_length = 250)
    option3 = models.CharField(max_length = 250)
    option4 = models.CharField(max_length = 250)
    answer = models.CharField(max_length= 1, choices = CHOICES, blank=True)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True, blank = True)

    def __str__(self):
        return self.question

Step 5

Add model to admin.py file

apiproject > api > admin.py

from django.contrib import admin
from .models import addQuestion

admin.site.register(addQuestion)

Step 6

Don’t forget to migrate the model changes. Like below:

Django API
Django API

Step 7

Create an superuser for admin panel .

Django API
Django API

After that run server by python manage.py runserver open url 127.0.0.1:8000/admin . Add data to models to create api like below :

Django API
Django API

Step 8 – Creating API

Here is the actual code for creating Django API using database :

apiproject > api > views.py

from django.shortcuts import render
from api.models import addQuestion
from django.core import serializers
from django.http import HttpResponse

def index(request):
    a = addQuestion.objects.all()
    serialized_obj = serializers.serialize('json',a)
    return HttpResponse(serialized_obj, content_type = 'application/json')

apiproject > apiproject> urls.py

from django.contrib import admin
from django.urls import path
from api import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index,name='index')
]

run python manage.py runserver  and here is the resulting Django API

Django API
Django API

What are serializers ?

Serializers allows us to convert complex data into plain text / simple accessible syntax . Complex syntax may be query sets or other database objects . It converts these object;s into python types (dictionary / list ) . And then can be converted to any content type like JSON. In django , serializers exists at core module . We uses serialize() function of it to convert data .

serialize()

serialize() is a method of serializers module which takes two arguments :

  • In which type , to convert example JSON
  • Complex Type / data to convert example query – sets .

Get data of API using unique id

Here is the final code to get specific data , by filling id to url .

apiproject > api > views.py

from django.shortcuts import render
from api.models import addQuestion
from django.core import serializers
from django.http import HttpResponse

def index(request):
        if request.method == 'GET':
            d = request.GET
            if 'id' in d:
                i = request.GET['id']
                dd = addQuestion.objects.filter(pk =i)
                serialized_obj = serializers.serialize('json',dd)
                return HttpResponse(serialized_obj, content_type = 'application/json')

            else:
                a = addQuestion.objects.all()
                serialized_obj = serializers.serialize('json',a)
                return HttpResponse(serialized_obj, content_type = 'application/json')

Output:

So , it is all about creating API with Django database . I hope you guys get it . Thanks !!!

50 thoughts on “Django API

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. I am extremely impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you customize it yourself? Either way keep up the nice quality writing, it is rare to see a great blog like this one today..

  2. I loved as much as you’ll receive carried out right here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you shield this hike.

  3. It’s correct time and energy to have ideas into the future and it’s the perfect time to be at liberty. I’ve truly see this placed in case I might simply just My spouse and i prefer to advocate people number of fascinating factors or maybe guidelines.. aplikasi berita saham You could may create upcoming articles about it document. I need to read through a lot more aspects of this!

  4. Heya i am for the first time here. I came across this board and I find It truly useful & it helped me out a lot. I hope to give something back and aid others like you helped me.

  5. Do you have a spam issue on this website; I also am a blogger, and I was wondering your situation; many of us have created some nice procedures and we are looking to swap techniques with others, please shoot me an e-mail if interested.

  6. A lot of thanks for all of your efforts on this website. Gloria really likes going through investigations and it is obvious why. A lot of people learn all of the dynamic medium you convey vital strategies on your blog and therefore cause participation from other ones on that subject matter while our own girl is in fact studying a whole lot. Enjoy the remaining portion of the new year. You’re the one carrying out a fantastic job.

  7. I just could not leave your web site prior to suggesting that I actually enjoyed the usual info an individual provide to your guests? Is gonna be again steadily in order to check up on new posts

  8. Thank you for the sensible critique. Me & my neighbor were just preparing to do some research on this. We got a grab a book from our local library but I think I learned more clear from this post. I’m very glad to see such great information being shared freely out there.

  9. I like the valuable information you provide in your articles. I’ll bookmark your blog and check again here frequently. I am quite sure I’ll learn plenty of new stuff right here! Best of luck for the next!

  10. I like the helpful information you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn many new stuff right here! Best of luck for the next!

  11. I’m not sure where you’re getting your info, but good topic. I needs to spend some time learning much more or understanding more. Thanks for fantastic info I was looking for this information for my mission.

  12. Youre so cool! I dont suppose Ive read anything like this before. So nice to find any individual with some unique thoughts on this subject. realy thank you for beginning this up. this website is something that is needed on the net, someone with a little originality. useful job for bringing one thing new to the web!

  13. I simply want to say I’m newbie to blogs and actually savored you’re web site. More than likely I’m going to bookmark your website . You definitely have impressive well written articles. Thanks a lot for sharing your web-site.

  14. An intriguing discussion is worth comment. I do believe that you can write more on this topic, it will not become a taboo subject but generally individuals are there are not enough to communicate in on such topics. To another location. Cheers

  15. My partner and I absolutely love your blog and find most of your post’s to be exactly I’m looking for. Does one offer guest writers to write content for you personally? I wouldn’t mind creating a post or elaborating on some of the subjects you write about here. Again, awesome weblog!

  16. Throughout this awesome design of things you secure an A just for effort. Where exactly you confused me ended up being in your particulars. You know, as the maxim goes, details make or break the argument.. And it could not be much more true here. Having said that, let me say to you precisely what did deliver the results. The authoring is actually pretty persuasive which is most likely the reason why I am taking the effort to comment. I do not make it a regular habit of doing that. Secondly, even though I can certainly notice the jumps in logic you make, I am not confident of how you appear to connect your details which inturn help to make the final result. For right now I shall yield to your position but wish in the foreseeable future you connect the dots much better.

  17. I have learn several just right stuff here. Definitely value bookmarking for revisiting. I surprise how a lot effort you set to make this kind of magnificent informative website.

  18. This is the precise blog for anybody who needs to seek out out about this topic. You notice so much its virtually onerous to argue with you (not that I really would need…HaHa). You undoubtedly put a brand new spin on a topic thats been written about for years. Great stuff, just nice!

  19. Hey very nice blog!! Man .. Beautiful .. Amazing .. I’ll bookmark your web site and take the feeds also…I am happy to find a lot of useful information here in the post, we need work out more techniques in this regard, thanks for sharing. . . . . .

  20. Have you ever thought about publishing an e-book or guest authoring on other blogs? I have a blog centered on the same ideas you discuss and would really like to have you share some stories/information. I know my viewers would appreciate your work. If you’re even remotely interested, feel free to shoot me an e mail.

  21. Hello, i believe that i saw you visited my website thus i got here to return the desire?.I am trying to in finding issues
    to improve my site!I assume its good enough to make use of some of your concepts!!

  22. Amazing blog! Is your theme custom made or did you download
    it from somewhere? A theme like yours with a few simple adjustements
    would really make my blog shine. Please let me know where you got your design. Bless
    you

  23. It has the just like you find out my mind! You gaze to understand so much close to this specific, like you published your ebook from it or something. I believe that you’re able to do with a few % to make the solution dwelling slightly, having said that in lieu of that will, that is definitely impressive site. A great examine. I’ll be returning. It has the just like you find out my mind! You gaze to understand so much close to this specific, like you published your ebook from it or something. I believe that you’re able to do with a few % to make the solution dwelling slightly, having said that in lieu of that will, that is definitely impressive site. A great examine. I’ll be returning.

  24. Hello,

    I’m running a SEO and SPY group buy service.

    See more at : https://spytools.win/

    I think you will be interested in this service which can save you a lot.

    We have PROMO price currently which is limited for the next 20 customers only!

    Do not reply to this message, email is not monitored.

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.