This is the heart of our To-Do API: the five task endpoints. Because every task belongs to a user, all of them need the login token from the last lesson.
The recipe for any endpoint
// The 4-step recipe for ANY endpoint (example: "add a task")
// 1. SCHEMA: what valid input looks like (task.schema.ts)
export const createTaskSchema = z.object({ title: z.string().trim().min(1).max(200) });
// 2. SERVICE: do the work, talk to the database (task.service.ts)
export function createTask(userId: number, data: CreateTaskInput) {
return prisma.task.create({ data: { ...data, userId } });
}
// 3. CONTROLLER: read req, call service, send res (task.controller.ts)
export async function create(req: Request, res: Response) {
const task = await taskService.createTask(res.locals.userId, req.body);
res.status(201).json(task);
}
// 4. ROUTE: connect the URL, add guards (task.routes.ts)
taskRouter.post("/", validate(createTaskSchema), task.create);Now let's write all five endpoints this way.
Step 1: The schemas (input rules)
Two schemas: one for creating (title required) and one for updating (everything optional, because PATCH only sends what changes). z.infer turns each schema into a TypeScript type for free.
import { z } from "zod";
export const createTaskSchema = z.object({
title: z.string().trim().min(1, "Title is required").max(200),
});
export const updateTaskSchema = z.object({
title: z.string().trim().min(1).max(200).optional(),
done: z.boolean().optional(),
});
export type CreateTaskInput = z.infer<typeof createTaskSchema>;
export type UpdateTaskInput = z.infer<typeof updateTaskSchema>;Install Zod if you haven't: bun add zod.
Step 2: The service (all the database work)
import { prisma } from "../../lib/prisma";
import { HttpError } from "../../utils/http-error";
import type { CreateTaskInput, UpdateTaskInput } from "./task.schema";
// Services talk to the database. They know nothing about req or res.
export async function listTasks(userId: number, page: number, limit: number) {
const [tasks, total] = await Promise.all([
prisma.task.findMany({
where: { userId },
orderBy: { createdAt: "desc" },
skip: (page - 1) * limit,
take: limit,
}),
prisma.task.count({ where: { userId } }),
]);
return { tasks, page, limit, total };
}
export async function getTask(userId: number, id: number) {
const task = await prisma.task.findFirst({ where: { id, userId } });
if (!task) throw new HttpError(404, "Task not found");
return task;
}
export function createTask(userId: number, data: CreateTaskInput) {
return prisma.task.create({ data: { ...data, userId } });
}
export async function updateTask(userId: number, id: number, data: UpdateTaskInput) {
await getTask(userId, id); // 404 if it's not this user's task
return prisma.task.update({ where: { id }, data });
}
export async function deleteTask(userId: number, id: number) {
await getTask(userId, id);
await prisma.task.delete({ where: { id } });
}Three things to notice:
- Every query has
userId. That one habit is what stops Asha from seeing Ravi's tasks. getTaskthrows a 404 when the task doesn't exist or isn't yours, andupdateTask/deleteTaskreuse it.- Pagination:
skip = (page โ 1) ร limitandtake = limit.Promise.allruns the list and the count at the same time.
Step 3: The controller (speaks HTTP)
import type { Request, Response } from "express";
import * as taskService from "./task.service";
import { HttpError } from "../../utils/http-error";
// Controllers read the request, call a service, and send the response. Nothing else.
function readId(req: Request) {
const id = Number(req.params.id);
if (!Number.isInteger(id) || id < 1) throw new HttpError(400, "Invalid task id");
return id;
}
export async function list(req: Request, res: Response) {
const page = Math.max(1, Number(req.query.page) || 1);
const limit = Math.min(50, Math.max(1, Number(req.query.limit) || 10));
res.json(await taskService.listTasks(res.locals.userId, page, limit));
}
export async function getOne(req: Request, res: Response) {
res.json(await taskService.getTask(res.locals.userId, readId(req)));
}
export async function create(req: Request, res: Response) {
const task = await taskService.createTask(res.locals.userId, req.body);
res.status(201).json(task);
}
export async function update(req: Request, res: Response) {
res.json(await taskService.updateTask(res.locals.userId, readId(req), req.body));
}
export async function remove(req: Request, res: Response) {
await taskService.deleteTask(res.locals.userId, readId(req));
res.status(204).send();
}The controller reads three kinds of input: req.params.id (the 5 in /tasks/5), req.query.page (the ?page=2) and req.body (the JSON). It also limits limit to 50, so nobody can ask for a million rows at once.
Step 4: The routes (the menu)
import { Router } from "express";
import * as task from "./task.controller";
import { validate } from "../../middlewares/validate";
import { requireAuth } from "../../middlewares/auth";
import { createTaskSchema, updateTaskSchema } from "./task.schema";
export const taskRouter = Router();
taskRouter.use(requireAuth); // every task route needs a logged-in user
taskRouter.get("/", task.list); // GET /api/tasks
taskRouter.get("/:id", task.getOne); // GET /api/tasks/5
taskRouter.post("/", validate(createTaskSchema), task.create); // POST /api/tasks
taskRouter.patch("/:id", validate(updateTaskSchema), task.update);// PATCH /api/tasks/5
taskRouter.delete("/:id", task.remove); // DELETE /api/tasks/5Connect it in app.ts with app.use("/api/tasks", taskRouter); and the API is complete.
The 5 endpoints at a glance
| Endpoint | Success | Common errors |
|---|---|---|
| GET /api/tasks?page=1&limit=10 | 200 + { tasks, page, limit, total } | 401 not logged in |
| GET /api/tasks/:id | 200 + the task | 400 bad id, 404 not found |
| POST /api/tasks | 201 + the new task | 400 invalid input |
| PATCH /api/tasks/:id | 200 + the updated task | 400, 404 |
| DELETE /api/tasks/:id | 204, empty body | 404 |
Try every endpoint
Log in first and put your token in a variable, so you don't have to paste it each time:
$TOKEN="paste-the-token-from-login-here"# Create$curl -X POST http://localhost:3000/api/tasks -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"title":"Learn Express"}'# List (page 1, 10 per page)$curl "http://localhost:3000/api/tasks?page=1&limit=10" -H "Authorization: Bearer $TOKEN"# Get one$curl http://localhost:3000/api/tasks/1 -H "Authorization: Bearer $TOKEN"# Mark it done$curl -X PATCH http://localhost:3000/api/tasks/1 -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"done":true}'# Delete$curl -X DELETE http://localhost:3000/api/tasks/2 -H "Authorization: Bearer $TOKEN"
These are the real responses from our test run:
{
"id": 1,
"title": "Learn Express",
"done": false,
"userId": 1,
"createdAt": "2026-11-19T13:40:38.323Z",
"updatedAt": "2026-11-19T13:40:38.323Z"
}{"id":2,"title":"Write my first API","done":false,"userId":1,...}{
"tasks": [
{"id":2,"title":"Write my first API","done":false,"userId":1,...},
{"id":1,"title":"Learn Express","done":false,"userId":1,...}
],
"page": 1,
"limit": 10,
"total": 2
}{"id":1,"title":"Learn Express","done":true,"userId":1,...}(empty)And the error cases, which matter just as much:
{
"error": "Invalid input",
"details": [
{
"field": "title",
"message": "Title is required"
}
]
}{
"error": "Invalid task id"
}{
"error": "Task not found"
}{
"error": "Task not found"
}{
"error": "Request body is not valid JSON"
}More APIs you'll write often, same recipe
| Need | Endpoint | In the service |
|---|---|---|
| Filter | GET /api/tasks?done=true | where: { userId, done: true } |
| Search | GET /api/tasks?search=milk | where: { userId, title: { contains: search, mode: "insensitive" } } |
| Sort | GET /api/tasks?sort=oldest | orderBy: { createdAt: "asc" } |
| Count | GET /api/tasks/stats | prisma.task.count({ where: { userId, done: true } }) |
| Bulk action | PATCH /api/tasks/complete-all | prisma.task.updateMany({ where: { userId }, data: { done: true } }) |
| My profile | GET /api/me | prisma.user.findUnique({ where: { id: userId }, select: { id: true, name: true, email: true } }) |
Key takeaways
- โOur To-Do API now has all five task endpoints, backed by PostgreSQL.
- โZod schemas validate and clean input, and give TypeScript types for free.
- โServices hold all database work and always filter by the logged-in user.
- โControllers read params, query and body, and choose the status code.
- โFilters, search, sorting and bulk actions are the same recipe with a different query.
Frequently asked questions
What does CRUD mean?
Create, Read, Update, Delete: the four things you can do with data. In REST they map to POST, GET, PATCH (or PUT) and DELETE. Most APIs are mainly CRUD.
PUT or PATCH?
PATCH changes only the fields you send ("just mark it done"). PUT replaces the whole thing, so you must send every field. Apps usually want PATCH. Our To-Do API uses PATCH.
Why paginate lists?
A user might have 10,000 tasks. Sending all of them at once is slow and wasteful. Pagination sends a page at a time, like ?page=2&limit=10, plus the total so the app can show page numbers.
Why return 404 for another user's task instead of 403?
Because 403 would confirm that task id exists. Returning 404 'not found' reveals nothing about other people's data. Filtering by userId in every query is what keeps users' data apart.
What is Zod?
Zod is a library to describe what valid data looks like ("title is a string, 1โ200 characters"). It checks incoming data, cleans it (for example trimming spaces) and gives you TypeScript types for free.
๐ง Quick check: CRUD APIs
1. Which endpoint marks task 5 as done?
2. What should DELETE return on success?
3. /api/tasks?page=2&limit=10 should returnโฆ
4. Where is the check that a task belongs to the logged-in user?
Checking your accessโฆ