Create a REST API to operate dynamodb with the Django REST Framework

Introduction

Create an api that operates on AWS DynamoDB with django REST Framework and boto3. Enable GET, POST, PUT, and DELETE operations.

Dynamodb table creation (preparation)

Prepare the following table in advance and put some data in it. Table name: Fruits hash key: Name

スクリーンショット 2020-08-10 22.16.19.png

Create a django project

Create django project (dynamo_operation) and app (api)

$ django-admin startproject dynamo_operation
$ cd dynamo_operation/
$ django-admin startapp api 

Edit setting.py

Add rest_framework and ʻapp config created earlier to setting.py`.

dynamo_operation/setting.py


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

Create model for DynamoDB request

In django, prepare model for DB creation and operation. Since the request to DynamoDB uses boto3, model is not necessary, but this time we preparedmodel (dynamo_model.py).

api/dynamo_model.py


class Fruit():
    def __init__(self, name):
        self.name = name

Edit views.py

api/views.py


from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response 
from api.dynamo_models import Fruit
from boto3 import client

dynamodb_client = client('dynamodb')

class DynamoRequest(APIView):
    #Whole GET
    def get(self, request):
        response = []
        items = dynamodb_client.scan(TableName='Fruits')['Items']
        for item in items:
            fruit = Fruit(item['Name']['S'])
            fruit.price = item.get('Price',{}).get('N', '')
            response.append(fruit.__dict__)
        return Response(response)
    
    def post(self, request):
        request_data = request.data
        item = {'Name': {'S': request_data['Name']}}

        if 'Price' in request_data:
            item['Price'] = {'N': request_data['Price']}

        dynamodb_client.put_item(
            TableName = 'Fruits',
            Item = item
        )
        return Response(status=status.HTTP_201_CREATED)


class DynamoDetailRequest(APIView):
    #Single GET
    def get(self, request, pk):
        item = dynamodb_client.get_item(
            TableName = 'Fruits',
            Key = {
                'Name': {'S': pk},
            }
        )['Item']
        fruit = Fruit(item['Name']['S'])
        fruit.price = item.get('Price',{}).get('N', '')
        return Response(fruit.__dict__)
    
    def put(self, request, pk):
        request_data = request.data

        item = dynamodb_client.get_item(
            TableName = 'Fruits',
            Key = {
                'Name': {'S': pk},
            }
        )['Item']

        price = item.get('Price',{}).get('N', '0')

        if 'Price' in request_data:
            price = request_data['Price']

        dynamodb_client.put_item(
            TableName = 'Fruits',
            Item = {
                'Name': {'S': item['Name']['S']},
                'Price': {'N': price}
            }
        )
        return Response(status=status.HTTP_200_OK)
    
    def delete(self, request, pk):
        dynamodb_client.delete_item(
            TableName = 'Fruits',
            Key = {
                'Name': {'S': pk},
            }
        )
        return Response(status=status.HTTP_204_NO_CONTENT)

Process the request with class which inherits ʻAPIView of rest_framework. DynamoRequest handles the request without the path parameter, andDynamoDetailRequest handles the request with the path parameter (pk). By inheriting ʻAPIView, it is possible to add the process corresponding to each method by preparing a function for each HTTP method.

Editing urls.py

api/urls.py


from django.urls import path
from api import views

urlpatterns = [
    path('api/', views.DynamoRequest.as_view()),
    path('api/<pk>/', views.DynamoDetailRequest.as_view())
]

Also edit ʻurls.py in the dynamo_opration` folder

dynamo_opration/urls.py


from django.urls import path, include

urlpatterns = [
    path('', include('api.urls')),
]

Check the operation with the curl command

start server

$ python manage.py runserver

GET (whole search)

$ curl http://127.0.0.1:8000/api/

#response
[{"name":"orange","price":"200"},{"name":"banana","price":"100"},{"name":"apple","price":"100"}]

POST

$ curl -X POST \
  -H 'Content-Type:application/json' \
  -d '{"Name": "peach", "Price": "400"}' \
  http://127.0.0.1:8000/api/

Table after POST request スクリーンショット 2020-08-10 23.16.38.png

The peach item has been added.

GET (single)

Get apple item

$ curl http://127.0.0.1:8000/api/apple/

#response
{"name":"apple","price":"100"}

PUT Change apple price from 100-> 200

$ curl -X PUT \
  -H 'Content-Type:application/json' \
  -d '{"Price": "200"}' \
  http://127.0.0.1:8000/api/apple/

Table after PUT request スクリーンショット 2020-08-10 23.21.52.png

DELETE Delete the peach item.

$ curl -X DELETE http://127.0.0.1:8000/api/peach/

Table after DELETE request スクリーンショット 2020-08-10 23.23.47.png

in conclusion

I created a REST API to operate DynamoDB with django REST Framework + boto3. This time, I prepared dynamodb_model.py to manage the model, but it may not have been necessary (I would like to improve the design around here in the future).

Recommended Posts

Create a REST API to operate dynamodb with the Django REST Framework
Create a Todo app with the Django REST framework
How to create a Rest Api in Django
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
Create a Todo app with Django REST Framework + Angular
The first API to make with python Djnago REST framework
Try to create a Qiita article with REST API [Environmental preparation]
Django REST framework A little useful to know.
I tried to create a table only with Django
Create an API with Django
How to create a submenu with the [Blender] plugin
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
Let's create it by applying Protocol Buffer to the API with Serverless Framework.
Create a homepage with django
Create APIs around user authentication with Django REST Framework
How to automatically generate API document with Django REST framework & POST from document screen
When you want to filter with Django REST framework
Create a tweet heatmap with the Google Maps API
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
Transit to the update screen with the Django a tag
Django REST framework with Vue.js
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
How to write custom validations in the Django REST Framework
How to reset password via API using Django rest framework
Probably the easiest way to create a pdf with Python3
Create a web API that can deliver images with Django
Create a social integration API for smartphone apps with Django
Operate Nutanix with REST API Part 2
Steps to create a Django project
[Django] Use MessagePack with Django REST framework
Create a file uploader with Django
I tried to create a RESTful API by connecting the explosive Python framework FastAPI to MySQL.
Create an alias for Route53 to CloudFront with the AWS API
A story about adding a REST API to a daemon made with Python
Implementation of CRUD using REST API with Python + Django Rest framework + igGrid
Rails users try to create a simple blog engine with Django
Create REST API that returns the current time with Python3 + Falcon
How to send a request to the DMM (FANZA) API with python
How to create a serverless machine learning API with AWS Lambda
Understand the benefits of the Django Rest Framework
CRUD GET with Nuxt & Django REST Framework ②
Miscellaneous notes about the Django REST framework
Easy REST API with API Gateway / Lambda / DynamoDB
[Django] I made a field to enter the date with 4 digit numbers
I changed the jwt token generator to simplejwt with Django Rest Auth.
How to deal with garbled characters in json of Django REST Framework
[AWS SAM] Create API with DynamoDB + Lambda + API Gateway
The easiest way to get started with Django
How to develop a cart app with Django
Let's create a REST API using SpringBoot + MongoDB
Create a dashboard for Network devices with Django!
Steps to create a Twitter bot with python
Save the object to a file with pickle
How to create a multi-platform app with kivy
Create a one-file hello world application with django
Create a translation tool with the Translate Toolkit
Implementing authentication in Django REST Framework with djoser
Create a REST API using the model learned in Lobe and TensorFlow Serving.
Solution when Not Found appears when hitting the Django REST Framework API from the outside
I failed to install django with pip, so a reminder of the solution