Create RESTful APIs with Django Rest Framework

Overview

This article walks you through the steps of a beginner developing a coupon distribution service for the iPhone with a RESTful API and swift. It is a very detour implementation because it was implemented while examining the technical elements one by one.

In the previous Customize TableView freely using Swift's TableViewCell, the app acquires the coupon information managed in the database through the API and displays it in list format. I created it to the point where it is done.

Next, we will modify this API into a RESTful API. In order to change the code drastically when remodeling, we will implement an API that only responds to all coupon information with GET once, and then modify it so that it will respond to the coupon information according to the request.

reference

environment

Mac OS 10.15 VSCode 1.39.2 pipenv 2018.11.26 Python 3.7.4 Django 2.2.6

procedure

Install Django Rest Framework

I'm creating a python project (virtual environment) with pipenv, so install the django rest framework there. Enter the pipenv shell and run the install command.

$ pipenv shell  #Enter the shell
$ pipenv install djangorestframework #Installation execution

Terminal being installed ... install-django-rest-framework.png

If you look inside the Pipfile after the installation is complete, you will see that djangorest framework has been added to[packages].


[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]

[packages]
django = "*"
djangorestframework = "*"

[requires]
python_version = "3.7"

Incorporate the Django Rest Framework

Just add the installed rest_framework to ʻINSTALLED_APPS = { in setting.py` under the project name directory.


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'coupon',
    'rest_framework', #add to
]

You're ready to use the Django Rest Framework.

Define Serializer

To use Rest Framework, you need a module called Serializer. Create and implement the Serializer file by yourself under the application directory.

I implemented it as follows.

coupon/serializer.py



from rest_framework import serializers #Import Django Rest Framework
from .models import Coupon # models.Import py coupon class

class CouponSerializer(serializers.ModelSerializer):
    class Meta:
        model = Coupon #Set the model name to be handled
        fields = '__all__'

In the code above, fields specifies the model fields (here coupon information) you want to respond to. If you want to respond to all items without specifying anything, use '__ all__'.

Modify View.py

Modify views.py for use with the Django Rest Framework.

The code looks like this: It's very simple.

views.py


from django.shortcuts import render
from .models import Coupon
from rest_framework import viewsets, filters
from .serializer import CouponSerializer


class CouponViewSet(viewsets.ModelViewSet):
    queryset = Coupon.objects.all() #Get all data
    serializer_class = CouponSerializer

Define URL_pattern

Edit ʻami_coupon_api / urls.pyandcoupon / urls.py. As a matter of fact, it seems better to edit from coupon / urls.py`.

The edited contents of coupon / urls.py are as follows.

coupon/urls.py


from django.urls import path
from . import views
from rest_framework import routers
from .views import CouponViewSet

router = routers.DefaultRouter()
router.register(r'coupons', CouponViewSet)

In the above, the 'coupons' part of r'coupons' is added after the request URL.

The edited contents of ʻami_coupon_api / urls.py` are as follows.

ami_coupon_api/urls.py


from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url, include
from coupon.urls import router as coupon_router

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/', include(coupon_router.urls)),
]

Check the operation using the curl command

Open a new terminal and try GET, POST, PUT requests. How to write a request is as follows. -X is an option to specify HTTP methods (GET, POST, PUT, etc.). Note that GET and POST could be executed without specifying.

$ curl -X [HTTP method] [URL] [Request parameters]

Try GET. Request parameters are not attached.

$ curl -X GET http://127.0.0.1:8000/api/coupons/

This json is returned.


[{"id": 1, "code": "0001", "benefit": "1,000 yen discount from payment", "explanation": "Limited to customers using 5,000 yen or more. Cannot be used with other coupons. "," store ":" All stores "," start ":" 2019-10-01 "," deadline ":" 2019-12-31 "," status ": true}, {" id ": 2," code ":" 0002 "," benefit ":" 10% off payment! "," explanation ":" Cannot be combined with other coupons "," store ":" Yurakucho store "," start ":" 2019-10 -01 "," deadline ":" 2019-12-31 "," status ": true}, {"id ": 3," code ":" 0003 "," benefit ":" [Halloween only] Disguise 30% off when you come to the store "," explanation ":" Only for customers who are disguised as 50% or more of the whole body (judgment is the feeling of the staff). Cannot be used with other coupons "," store ":" Kanda store "," start ":" 2019-10-31 "," deadline ":" 2019-10-31 "," status ": true}, {"id ": 4," code ":" 0004 ", "benefit": "[September only] Moon-viewing dumpling service", "explanation": "Given a moon-viewing dumpling to customers who wish! Can be used with other coupons!", "Store": "All stores" , "start": "2019-09-01", "deadline": "2019-09-30", "status": true}, {"id": 5, "code": "0005", "benefit" : "[Rainy days only] 15% off payment", "explanation": "Available only when coupons are delivered. Cannot be combined with other coupons", "store": "All stores", "start" ":" 2019-10-01 "," deadline ":" 2019-12-31 "," status ": false}, {" id ": 6," code ":" 0006 "," benefit ":" [ Sunday only] Cheers Tequila Service "," explanation ":" We will serve Tequila for the number of people. Can be used with other coupons. "," store ":" Kanda Store "," start ":" 2019-11-03 " , "d eadline ":" 2019-12-01 "," status ": true}]


Try POST.

curl -X POST http://127.0.0.1:8000/api/coupons/ -d "code=0007" -d "benefit=From checkout 19%pull" -d "explanation=Limited to December 29th-December 31st." -d "store=Kanda store" -d "start=2019-12-29" -d "deadline=2019-12-31" -d "status=true"

If it goes well, the POSTed data will be returned in json.


{"id": 7, "code": "0007", "benefit": "19% discount from checkout", "explanation": "December 29-31 only.", "Store": "Kanda store", "start": "2019-12-29", "deadline": "2019-12-31", "status": true}


Try PUT. At the time of PUT, it is necessary to specify the HTTP method. More importantly, you need to ** specify the table's primary key in the URL **. In the coupon model, "id" is the primary key, so specify the id of the data you want to overwrite (7 in this case) at the end of the URL.

curl -X PUT http://127.0.0.1:8000/api/coupons/7/ -d "code=0007" -d "benefit=From checkout 19%pull" -d "explanation=Limited to December 29th-December 31st. Cannot be used with other coupons" -d "store=Kanda store" -d "start=2019-12-29" -d "deadline=2019-12-31" -d "status=true"

If all goes well, the overwritten data will be returned in json.


{"id": 7, "code": "0007", "benefit": "19% discount from checkout", "explanation": "December 29-31 only. Combined with other coupons Impossible "," store ":" Kanda store "," start ":" 2019-12-29 "," deadline ":" 2019-12-31 "," status ": true}


Try DELETE. Execute the POST request again to create a coupon with id = 8. Make sure you've added a coupon with id = 8 on your GET request or on the Django server console.

Next, delete the coupon with id = 8 in the request below. As with PUT, you need to specify the primary key of the coupon to be deleted.

curl -X DELETE http://127.0.0.1:8000/api/coupons/8/

If all goes well, nothing will be returned. Make sure the coupon with id = 8 has been deleted in your GET request or in the Django server console.

So far, you have a basic Rest Framework. From here, Add filters and authentication functions to get only coupons that meet the conditions.

Recommended Posts

Create RESTful APIs with Django Rest Framework
Create APIs around user authentication with Django REST Framework
Django REST framework with Vue.js
Login with django rest framework
Create a Todo app with Django REST Framework + Angular
Create a Todo app with the Django REST framework
[Django] Use MessagePack with Django REST framework
CRUD GET with Nuxt & Django REST Framework ②
CRUD POST with Nuxt & Django REST Framework
CRUD GET with Nuxt & Django REST Framework ①
Create a REST API to operate dynamodb with the Django REST Framework
Django REST framework basics
Django Rest Framework Tips
CRUD PUT, DELETE with Nuxt & Django REST Framework
Implementing authentication in Django REST Framework with djoser
More new user authentication methods with Django REST Framework
Create an API with Django
Create a homepage with django
When you want to filter with Django REST framework
Implement APIs at explosive speed using Django REST Framework
Django REST framework stumbling block
Implement hierarchical URLs with drf-nested-routers in Django REST framework
Create a file uploader with Django
Implementation of CRUD using REST API with Python + Django Rest framework + igGrid
Logical deletion in Django, DRF (Django REST Framework)
Understand the benefits of the Django Rest Framework
ng-admin + Django REST framework ready-to-create administration tool
Miscellaneous notes about the Django REST framework
Create an update screen with Django Updateview
Create your first app with Django startproject
Django REST Framework + Clean Architecture Design Consideration
How to deal with garbled characters in json of Django REST Framework
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
Internationalization with django
How to automatically generate API document with Django REST framework & POST from document screen
Create a dashboard for Network devices with Django!
Create Nginx + uWSGI + Python (Django) environment with docker
Django REST framework A little useful to know.
CRUD with Django
Create a one-file hello world application with django
Implement JWT login functionality in Django REST framework
How to create a Rest Api in Django
Sometimes you want to access View information from Serializer with DRF (Django REST Framework)
I tried to create a table only with Django
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
Create Python version Lambda function (+ Lambda Layer) with Serverless Framework
List method for nested resources in Django REST framework
Create a Todo app with Django ③ Create a task list page
[Django Rest Framework] Customize the filter function using Django-Filter
Dynamically create tables in schema with Django, dynamically generate models
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
Create a Todo app with Django ⑤ Create a task editing function
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
Create a django environment with docker-compose (MariaDB + Nginx + uWSGI)
Django 1.11 started with Python3.6
Development digest with Django
Create a Django schedule
Django python web framework
Output PDF with Django