Menu
CoddyTech

JSONのバリデーションエラー

CoddyのDjangoジャーニー「JSON API」セクションの一部。レッスン 7/19。

現時点では、タイトルのないPOSTを送るとKeyErrorでクラッシュし、Djangoは500 Server Errorを返しますが、これではプログラムに何を修正すればよいか何も伝わりません。

データに問題がある場合は、400 Bad Requestを返し、Djangoのフォームがエラーを保持する方法と同じように、フィールドごとに1つのメッセージをJSONで示して、何が間違っているのかを伝えましょう。本屋で本の出版年を確認する場合:

errors = {}
year = data.get("year")
if not isinstance(year, int) or year < 0:
    errors["year"] = "Enter the year as a whole number."
if errors:
    return JsonResponse({"errors": errors}, status=400)

残る落とし穴が2つあります。スペースだけのタイトルは空ではありませんが、" ".strip()は""になります。JSONではない本文を渡すと、json.loadsはjson.JSONDecodeErrorを発生させます。tryとexceptでこれを捕捉し、クラッシュする代わりに400を返しましょう。

challenge icon

チャレンジ

中級

POST /api/tasks/ が不正なデータをステータス 400 で拒否するようにします。

  1. task_list で、json.loads の周りに json.JSONDecodeError の処理を追加し、{"error": "The body is not valid JSON."} を返します。
  2. タイトルが指定されていないか、空白を取り除いた後に空の場合は、何も保存せず、{"errors": {"title": "This field is required."}} を返します。
  3. それ以外の場合は、空白を取り除いたタイトルでタスクを作成します。

「Shell」タブでは、以下の行を実行すると「This field is required.」と表示されます。

from django.test import Client; print(Client().post("/api/tasks/", {"title": "  "}, content_type="application/json").json())

自分で試してみよう

import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from .models import Task


def task_to_dict(task):
    return {
        "id": task.id,
        "title": task.title,
        "done": task.done,
        "priority": task.priority,
    }


def home(request):
    return render(request, "tasks/home.html", {"tasks": Task.objects.all()})


def stats(request):
    data = {
        "total": Task.objects.count(),
        "done": Task.objects.filter(done=True).count(),
    }
    return JsonResponse(data)


@csrf_exempt
def task_list(request):
    if request.method == "POST":
        data = json.loads(request.body)
        task = Task.objects.create(
            title=data["title"],
            priority=data.get("priority", "normal"),
        )
        return JsonResponse(task_to_dict(task), status=201)
    tasks = Task.objects.all()
    done = request.GET.get("done")
    if done == "true":
        tasks = tasks.filter(done=True)
    elif done == "false":
        tasks = tasks.filter(done=False)
    return JsonResponse([task_to_dict(task) for task in tasks], safe=False)


def task_detail(request, pk):
    task = Task.objects.filter(pk=pk).first()
    if task is None:
        return JsonResponse({"error": "Task not found"}, status=404)
    return JsonResponse(task_to_dict(task))

JSON APIのすべてのレッスン

自分で練習してみよう: Djangoプレイグラウンド