Create your first API -> Response

Create your first API -> Response

ยท

2 min read

we start from zero steps, first, we should create a Django project by the following command:

django-admin startproject mysite

then you can see these folders and files in your root:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

we create our app by the following command:

python manage.py startapp polls
polls/
    __init__.py
    admin.py
    apps.py
    models.py
    tests.py
    views.py
    migrations/
        __init__.py

Now we should tell the project that we have an app whose name is polls so we change the settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'polls',
]

we should introduce the URLs of apps(polls) to the project so we modify urls.py which is in the mysite folder ( mysite is our project):

from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('app1', include('polls.urls')),
]
# 'app1' is alternative you can change it to other name 'app2', 'hi', goodby or other serious or funny word! :)

then we modify urls.py in the 'polls' app:

from django.urls import path
from . import views
urlpatterns = [
    path('hi1/', views.Home3),
]
# dont worry i will explaine what is home1!

now we should define what will happen if we enter http://127.0.0.1:8000/app1/hi1/

so we modify view.py in the 'polls' folder:

from rest_framework.response import Response
from rest_framework.views import APIView

class Home3(APIView):
    def get(self, request):
        return Response({'name': 'John'})

Now if we enter http://127.0.0.1:8000/app1/hi1 we can see this page:

what does this information mean?

Home3 : name of the class which you define in your view.py

1: HTTP method which you can access to this data( { "name": " John"})

2: URLs that you enter by that

3: status code

4: HTTP method which is allowed

5: type of data which is sent ( json)

6: it will be explained :)

7:data which is sent to the user

ย