I tried to make a Web API

Introduction

This article is for the 21st day of Volare Advent Calendar 2019.

This time I made the API of iOS application for the first time. Partly because I'm studying, I tried to create an API using Django REST Framework, so I'd like to write about it: relaxed: The article on the iOS side of the created application is here

About the app

The main target for creating apps is college students living alone like us: dark_sunglasses: For details on how the app was decided, It's a hassle to think about menus when cooking for yourself, but existing apps search by looking at what's in the refrigerator. → The target of existing ones is for people with families

I like it. I found it convenient to have an app that automatically presents menus by entering dislikes! → Basically, I don't make much, I want to make what I like at any time (the refrigerator doesn't have much ingredients: ghost :)

I decided to make it from such a point! (If you don't have the same concept, let's make one: relaxed :)

Team development together, Ryu-chan explains the app. This time I was in charge of this backend.

What I implemented

On the backend, we have implemented the following 5 features!

I was in charge of three of them, so I will write about that part!

User authentication

from main.models import User, FoodConfigParam
from main.serializers import AuthSerializer
from rest_framework.generics import GenericAPIView
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.response import Response
import random

from rest_framework_jwt.settings import api_settings
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

class RegisterAuthView(GenericAPIView):
    permission_classes = ()
    serializer_class = AuthSerializer
    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        #Returns token if uuid is registered
        if User.objects.filter(uuid=serializer.data['uuid']):
            user = User.objects.get(uuid=serializer.data['uuid'])
            payload = jwt_payload_handler(user)
            return Response({
                'token': jwt_encode_handler(payload),
            })

        user = User.objects.create_user(uuid=serializer.data['uuid'])
        user.save()
        if not user:
            raise AuthenticationFailed()
        payload = jwt_payload_handler(user)
        #Add default ingredients when registering as a user
        user = User.objects.filter(uuid=serializer.data['uuid']).last()
        food = FoodConfigParam()
        food.create_defaultfood(user=user)
        return Response({
            'token': jwt_encode_handler(payload),
        })

Check if there is a user in the DB that matches the UUID sent, and if not, create a user.

Ingredient list display and batch change for each user

from main.models import FoodConfigParam
from main.serializers import FoodConfigParamSerializer
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
from rest_framework.response import Response

class UserFoodConfig(GenericAPIView):
    queryset = FoodConfigParam.objects.all()
    serializer_class = FoodConfigParamSerializer

    def get(self, request):
        foodConfigParams = FoodConfigParam.objects.filter(user=request.user)
        serializer = FoodConfigParamSerializer(foodConfigParams, many=True)
        return Response({'data': serializer.data})

    def put(self, request):
        res = []
        for config in request.data['data']:
            name = config['name']
            rate = config['rate']
            #Extract the ones that match the registered user and the ingredient name
            foodConfigParam = FoodConfigParam.objects.get(user=request.user, name=name)
            #Change probability
            serializer = FoodConfigParamSerializer(foodConfigParam, data={'rate': rate}, partial=True)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            res.append(serializer.data)
        return Response({'data': res})

The ones that match the user and the ingredient name are extracted, and the appearance rate is changed.

What was difficult

The API I made did not work well, or it worked but it worked unexpectedly when connected to iOS. On the iOS side, it seems that there are various things such as trying not to write logic as much as possible and reducing the number of communications, I felt that if I didn't have more knowledge on the front side, I wouldn't be able to communicate and it would be difficult ... I consulted with the iOS side and proceeded while discussing how easy it would be to do this, and I learned.

in conclusion

This time I was making something that works for the time being, so I still don't understand RESTful: cry: So, I knew the goodness of django-rest-framework and decided to study so that I could make the most of it. Thank you for reading to the end.

Recommended Posts

I tried to make a Web API
I tried to make a ○ ✕ game using TensorFlow
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
I tried to make a "fucking big literary converter"
I tried to make a castle search API with Elasticsearch + Sudachi + Go + echo
I tried to make a simple image recognition API with Fast API and Tensorflow
I tried to make a stopwatch using tkinter in python
I tried to make a simple text editor using PyQt
I tried to create a linebot (implementation)
I tried to create a linebot (preparation)
I tried to touch the COTOHA API
I tried benchmarking a web application framework
[5th] I tried to make a certain authenticator-like tool with python
I tried to make a system that fetches only deleted tweets
Rubyist tried to make a simple API with Python + bottle + MySQL
[2nd] I tried to make a certain authenticator-like tool with python
I tried to make a regular expression of "amount" using Python
I tried to make a regular expression of "time" using Python
[3rd] I tried to make a certain authenticator-like tool with python
I tried to make a regular expression of "date" using Python
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
I tried to make a todo application using bottle with python
[4th] I tried to make a certain authenticator-like tool with python
[1st] I tried to make a certain authenticator-like tool with python
I tried to make a strange quote for Jojo with LSTM
I tried to make a mechanism of exclusive control with Go
I tried to debug.
I tried to make a motion detection surveillance camera with OpenCV using a WEB camera with Raspberry Pi
I tried to paste
I want to make matplotlib a dark theme
I tried web scraping to analyze the lyrics.
I tried to build a super-resolution method / SRCNN ①
I want to make a game with Python
I tried to touch the API of ebay
I tried to make AI for Smash Bros.
I read "How to make a hacking lab"
I tried to generate a random character string
I tried to build a super-resolution method / SRCNN ③
I tried to build a super-resolution method / SRCNN ②
I tried to introduce a serverless chatbot linked with Rakuten API to Teams
Python: I tried to make a flat / flat_map just right with a generator
I tried to make a face diagnosis AI for a female professional golfer ①
I tried to make a face diagnosis AI for a female professional golfer ②
I tried to make a calculator with Tkinter so I will write it
I tried to make a skill that Alexa will return as cold
I tried to make a url shortening service serverless with AWS CDK
I tried to make PyTorch model API in Azure environment using TorchServe
I want to make a web application using React and Python flask
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
I tried to create a table only with Django
I tried to learn PredNet
I tried to make a simple mail sending application with tkinter of Python
I tried to organize SVM.
[Patent analysis] I tried to make a patent map with Python without spending money
I tried to implement a pseudo pachislot in Python
Continuation ・ I tried to make Slackbot after studying Python3
I tried to implement a recommendation system (content-based filtering)
[ES Lab] I tried to develop a WEB application with Python and Flask ②
[Go + Gin] I tried to build a Docker environment
I tried to uncover our darkness with Chatwork API