All good or a client error
200— success201— created204— success, no response body400— invalid data401— you need to log in403— no permission404— not found
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.
The address names the data, and the HTTP method names the action on it.
| Request | What it does | Successful response |
|---|---|---|
GET /tasks | Returns the list | 200 OK |
POST /tasks | Creates a task | 201 Created |
GET /tasks/5 | Returns one task | 200 OK |
PATCH /tasks/5 | Changes some fields | 200 OK |
DELETE /tasks/5 | Deletes | 204 No Content |
The client looks at the code first and only then reads the response body.
200 — success201 — created204 — success, no response body400 — invalid data401 — you need to log in403 — no permission404 — not found500 — an error in the application code502 — the web server got no proper response from the application503 — the service is temporarily unavailableA 5xx error means the cause must be looked for on the server, not in the request.
Flask turns a dictionary into JSON itself. A list is better passed through jsonify.
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")
A simple JSON response can be returned with built-in tools. For a large API people usually take Django REST framework.
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.
On a page this is done by the fetch function. Check the status code: fetch does not treat 404 as an error.
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.
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.
Links checked on .
Build a blog API with a real database.