REST
easy 26 minREST is a style for network APIs: everything worth naming gets an address, and a small shared set of HTTP methods acts on it.
A tiny REST server, in memory
Read it, run it, change a line and run it again.
Loading editor…
Follow the promises: GET changes nothing, PUT and DELETE can be repeated, POST is repeated safely only with a key, and If-Match refuses an old version.
The same in TypeScript
// npm install express zod (Express 5)import express, { type NextFunction, type Request, type Response } from "express";import { z } from "zod";const app = express();app.use(express.json({ limit: "100kb" }));const UserIn = z.object({ name: z.string().min(1).max(100), email: z.email(), age: z.number().int().min(0).max(150).optional(),});type User = z.infer<typeof UserIn> & { id: number };const users = new Map<number, User>();let nextId = 1;// One error shape for the whole API.const problem = (res: Response, status: number, title: string, extra: object = {}) => res.status(status).type("application/problem+json").json({ title, status, ...extra });// Only these names may be sorted by. Never pass the raw value to SQL.const SORT = new Set<keyof User>(["id", "name", "email"]);app.get("/api/users", (req, res) => { const page = Math.max(1, parseInt(String(req.query.page ?? "1"), 10) || 1); const limit = Math.min(100, Math.max(1, parseInt(String(req.query.limit ?? "10"), 10) || 10)); const sort = String(req.query.sort ?? "id") as keyof User; if (!SORT.has(sort)) return void problem(res, 400, "Unknown sort field"); const search = String(req.query.search ?? "").toLowerCase(); const sign = req.query.order === "desc" ? -1 : 1; const all = [...users.values()] .filter((u) => u.name.toLowerCase().includes(search) || u.email.toLowerCase().includes(search)) .sort((a, b) => sign * (String(a[sort]).localeCompare(String(b[sort]), "en", { numeric: true }) || a.id - b.id)); const totalPages = Math.max(1, Math.ceil(all.length / limit)); res.json({ data: all.slice((page - 1) * limit, page * limit), pagination: { page, limit, total: all.length, totalPages, hasNext: page < totalPages, hasPrev: page > 1 }, });});app.get("/api/users/:id", (req, res) => { const user = users.get(Number(req.params.id)); if (!user) return void problem(res, 404, "User not found"); res.json(user);});app.post("/api/users", (req, res) => { const parsed = UserIn.safeParse(req.body); if (!parsed.success) return void problem(res, 422, "Validation failed", { errors: z.flattenError(parsed.error).fieldErrors }); const user = { id: nextId++, ...parsed.data }; users.set(user.id, user); res.status(201).location("/api/users/" + user.id).json(user);});app.put("/api/users/:id", (req, res) => { const id = Number(req.params.id); if (!users.has(id)) return void problem(res, 404, "User not found"); const parsed = UserIn.safeParse(req.body); if (!parsed.success) return void problem(res, 422, "Validation failed"); users.set(id, { id, ...parsed.data }); res.json(users.get(id));});app.delete("/api/users/:id", (req, res) => { if (!users.delete(Number(req.params.id))) return void problem(res, 404, "User not found"); res.status(204).end();});// Last: hide the details of unexpected errors.app.use((err: Error & { status?: number }, _req: Request, res: Response, next: NextFunction) => { console.error(err); if (res.headersSent) return next(err); const status = err.status && err.status < 500 ? err.status : 500; problem(res, status, status < 500 ? "Bad request" : "Something went wrong");});app.listen(3000);// ---- A client ----async function createUser(base: string, token: string, body: z.infer<typeof UserIn>): Promise<User> { const res = await fetch(base + "/api/users", { method: "POST", headers: { Authorization: "Bearer " + token, "Content-Type": "application/json", Accept: "application/json", "Idempotency-Key": crypto.randomUUID(), // keep the same key when you retry }, body: JSON.stringify(body), signal: AbortSignal.timeout(10_000), }); if (!res.ok) throw new Error("HTTP " + res.status); // fetch does not throw on 4xx or 5xx return (await res.json()) as User;}The same in Go
// Go 1.22 or later: method and wildcard patterns in net/httppackage mainimport ( "encoding/json" "log" "net/http" "strconv" "sync")type User struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"`}var ( mu sync.RWMutex users = map[int]User{} nextID = 1)func write(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") // before WriteHeader w.WriteHeader(status) json.NewEncoder(w).Encode(v)}func list(w http.ResponseWriter, r *http.Request) { mu.RLock() out := make([]User, 0, len(users)) for _, u := range users { out = append(out, u) } mu.RUnlock() write(w, http.StatusOK, out)}func create(w http.ResponseWriter, r *http.Request) { var u User body := http.MaxBytesReader(w, r.Body, 1<<20) if err := json.NewDecoder(body).Decode(&u); err != nil { http.Error(w, "invalid JSON", http.StatusBadRequest) return } mu.Lock() u.ID = nextID nextID++ users[u.ID] = u mu.Unlock() w.Header().Set("Location", "/api/users/"+strconv.Itoa(u.ID)) write(w, http.StatusCreated, u)}func get(w http.ResponseWriter, r *http.Request) { id, _ := strconv.Atoi(r.PathValue("id")) mu.RLock() u, ok := users[id] mu.RUnlock() if !ok { http.Error(w, "not found", http.StatusNotFound) return } write(w, http.StatusOK, u)}func remove(w http.ResponseWriter, r *http.Request) { id, _ := strconv.Atoi(r.PathValue("id")) mu.Lock() _, ok := users[id] delete(users, id) mu.Unlock() if !ok { http.Error(w, "not found", http.StatusNotFound) return } w.WriteHeader(http.StatusNoContent)}func main() { mux := http.NewServeMux() mux.HandleFunc("GET /api/users", list) mux.HandleFunc("POST /api/users", create) mux.HandleFunc("GET /api/users/{id}", get) mux.HandleFunc("DELETE /api/users/{id}", remove) log.Fatal(http.ListenAndServe(":3000", mux)) // other methods get 405 and Allow}