[Python / Django] Create a web API that responds in JSON format

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.

Modify the code created in the previous Try using Django's template function so that it responds in JSON format. There is a convenient framework called Django Rest Framework, but first I will write it without using Django Rest Framework etc. for the purpose of understanding the mechanism.

reference

Introduction to Python Django (6)

environment

Mac OS 10.15 VSCode 1.39.2 pipenv 2018.11.26 Python 3.7.4 Django 2.2.6

procedure

Modify views.py

Import the json module to convert the data to json format. Add ʻimport json` to your code.

Use json.dumps to add a program that takes a structure as input and creates a json format string. The code that creates the structure uses the params = {} part of the original code as it is.

Add code to create a json format string. We are passing the structure data params as an argument. json_str = json.dumps(params, ensure_ascii=False, indent=2)

The return value is simply a Json-formatted string with the HttpResponse method. return HttpResponse(json_str)

The modified views.py is here.

views.py


from django.shortcuts import render
from django.http import HttpResponse
import json #Added

def coupon(request):
    if 'coupon_code' in request.GET:
        coupon_code = request.GET['coupon_code']
        if coupon_code == '0001':
            benefit = '1000 yen discount coupon!'
            deadline = '2019/10/31'
            message = ''
        elif coupon_code == '0002':
            benefit = '10%Discount coupon!'
            deadline = '2019/11/30'
            message = ''
        else:
            benefit = 'NA'
            deadline = 'NA'
            message = 'No coupons available'

        params = {
            'coupon_code':coupon_code,
            'coupon_benefits':benefit,
            'coupon_deadline':deadline,
            'message':message,
        }
        #Generate json format string
        json_str = json.dumps(params, ensure_ascii=False, indent=2) 
        return HttpResponse(json_str)

Operation check

Save the code and start django's server.

If you access http://127.0.0.1:8000/coupon/?coupon_code=0001 with the curl command from the terminal, you can get the value with json. ami_coupon_api-test-curl-mask.png

Next, when I accessed http://127.0.0.1:8000/coupon/?coupon_code=0001 with a browser, the data in json format was displayed. ami_coupon_api-test-web.png

that's all.

Next time, Implementation on the application side that responds to coupon information (swift)

Recommended Posts

[Python / Django] Create a web API that responds in JSON format
Tornado-Let's create a Web API that easily returns JSON with JSON
Create a web API that can deliver images with Django
Create a JSON object mapper in Python
How to create a JSON file in Python
How to create a Rest Api in Django
Easily format JSON in Python
Create a function in Python
Create a dictionary in Python
I tried to create a class that can easily serialize Json in Python
[LINE Messaging API] Create a rich menu in Python
In Python, create a decorator that dynamically accepts arguments Create a decorator
[Django3] Display a web page in Django3 + WSL + Python virtual environment
Let's create a script that registers with Ideone.com in Python.
Create code that outputs "A and pretending B" in python
Create a binary file in Python
Create Gmail in Python without API
Hit the web API in Python
Create a Kubernetes Operator in Python
Create a random string in Python
Create a LINE Bot in Django
[LINE Messaging API] Create a BOT that connects with someone with Python
A class that summarizes frequently used methods in twitter api (python)
Python: Reading JSON data from web API
Create a simple GUI app in Python
[Python] Create a LineBot that runs regularly
[GPS] Create a kml file in Python
Create a web service in Flask-SQLAlchemy + PostgreSQL
I made a web application in Python that converts Markdown to HTML
I tried to develop a Formatter that outputs Python logs in JSON
Let's create a customer database that automatically issues a QR code in Python
format in python
Create a Vim + Python test environment in 1 minute
Create a GIF file using Pillow in Python
A memo that I wrote a quicksort in Python
I want to create a window in Python
Create a standard normal distribution graph in Python
Create a virtual environment with conda in Python
Create a page that loads infinitely with python
A program that removes duplicate statements in Python
Create a web map using Python and GDAL
Steps to develop a web application in Python
Create a simple momentum investment model in Python
Python: Create a class that supports unpacked assignment
Create a new page in confluence with Python
Create a datetime object from a string in Python (Python 3.3)
Create a Photoshop format file (.psd) with python
Create a package containing global commands in Python
Until you create a new app in Django
Create a MIDI file in Python using pretty_midi
Create a loop antenna pattern in Python in KiCad
[Docker] Create a jupyterLab (python) environment in 3 minutes!
Create a web server in Go language (net/http) (2)
Create a Python image in Django without a dummy image file and test the image upload
Create a plugin that allows you to search Sublime Text 3 tabs in Python
I want to create a priority queue that can be updated in Python (2.7)
Create a Django project and application in a Python virtual environment and start the server
[Django] Create a form that automatically fills in the address from the zip code
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
Deploy a Python 3.6 / Django / Postgres web app on Azure
Create a Django schedule