REST API: a site that returns data

You need an API when the server answers not with a page but with data: for a JavaScript site, a mobile app or another program.

Telegraph operators at work at a signal office in Boulogne, 1919

The main rules of REST

The address names the data, and the HTTP method names the action on it.

HTTP methods for a task list
RequestWhat it doesSuccessful response
GET /tasksReturns the list200 OK
POST /tasksCreates a task201 Created
GET /tasks/5Returns one task200 OK
PATCH /tasks/5Changes some fields200 OK
DELETE /tasks/5Deletes204 No Content

Status codes

The client looks at the code first and only then reads the response body.

All good or a client error

  • 200 — success
  • 201 — created
  • 204 — success, no response body
  • 400 — invalid data
  • 401 — you need to log in
  • 403 — no permission
  • 404 — not found

Server error

  • 500 — an error in the application code
  • 502 — the web server got no proper response from the application
  • 503 — the service is temporarily unavailable

A 5xx error means the cause must be looked for on the server, not in the request.

An API in Flask

Flask turns a dictionary into JSON itself. A list is better passed through jsonify.

Flask: a JSON API with a task list
from flask import Flask, jsonify, request

app = Flask(__name__)
tasks = {}
next_id = 1

@app.get("/tasks")
def list_tasks():
    return jsonify(list(tasks.values()))

@app.post("/tasks")
def create_task():
    global next_id
    data = request.get_json(silent=True) or {}
    title = str(data.get("title", "")).strip()
    if not title:
        return {"error": "The title field is required"}, 400
    task = {"id": next_id, "title": title, "done": False}
    tasks[next_id] = task
    next_id += 1
    return task, 201

@app.patch("/tasks/<int:task_id>")
def update_task(task_id):
    task = tasks.get(task_id)
    if task is None:
        return {"error": "Task not found"}, 404
    data = request.get_json(silent=True) or {}
    if "done" in data:
        task["done"] = bool(data["done"])
    return task

@app.delete("/tasks/<int:task_id>")
def delete_task(task_id):
    if tasks.pop(task_id, None) is None:
        return {"error": "Task not found"}, 404
    return "", 204

client = app.test_client()
print(client.post("/tasks", json={}).status_code, "empty task")
created = client.post("/tasks", json={"title": "Write an API"})
print(created.status_code, created.json)
print(client.patch("/tasks/1", json={"done": True}).json)
print(client.get("/tasks").json)
print(client.delete("/tasks/1").status_code, "deleted")
print(client.delete("/tasks/1").status_code, "deleting again")

An API in Django

A simple JSON response can be returned with built-in tools. For a large API people usually take Django REST framework.

tasks/views.py
import json

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from .models import Task

@csrf_exempt  # for the tutorial only: a real API needs authentication
@require_http_methods(["GET", "POST"])
def tasks(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            title = str(data.get("title", "")).strip()
        except (json.JSONDecodeError, AttributeError):
            return JsonResponse({"error": "Invalid JSON"}, status=400)
        if not title:
            return JsonResponse({"error": "The title field is required"}, status=400)
        task = Task.objects.create(title=title)
        return JsonResponse({"id": task.id, "title": task.title}, status=201)
    return JsonResponse(list(Task.objects.values("id", "title")), safe=False)

The safe=False parameter is needed because by default JsonResponse accepts only a dictionary.

How to call an API from the browser

On a page this is done by the fetch function. Check the status code: fetch does not treat 404 as an error.

JavaScript
async function addTask(title) {
  const response = await fetch("/tasks", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title }),
  });

  if (!response.ok) {
    const problem = await response.json();
    throw new Error(problem.error);
  }

  return response.json();
}

If the site and the API live at different addresses, the browser blocks the response until the server allows it with CORS headers. Flask has the Flask-CORS extension for this.

Where FastAPI fits

If the project is only an API, have a look at FastAPI: it checks data against type hints and builds documentation itself. The REST principles stay the same.

First API with FastAPI — the same task list step by step: Pydantic models, status codes, the /docs page and tests.

Next: the second project

Build a blog API with a real database.