Part 03 · Web এর ভাষা
REST and Resource Modeling
Action এর বদলে resource দিয়ে ভাবা, আর এমন URL design করা যা client আন্দাজ করতে পারে।
⏱ 1-2 ঘণ্টা · Station 36 / 153
Forty endpoints and nobody can guess the forty-first
একটা team এর API একটা একটা feature করে বড় হয়েছে। দুই বছর পর সেখানে আছে /getUserById, /fetchUserOrders, /createNewOrder, /order/cancel, /cancelOrderItem, /updateUserEmailAddress, আর আরো ত্রিশটা। নতুন যে frontend developer আসে, সবাই একই প্রশ্ন করে: get নাকি fetch? /order নাকি /orders? Cancel এর জন্য POST নাকি GET? প্রতিটা endpoint নিজের মতো shape এ error দেয়। কেউ URL আন্দাজ করতে পারে না, প্রতিবার খুঁজে দেখতে হয়।
এবার এমন একটা API দেখো, যেটা action এর বদলে জিনিস ঘিরে design করা:
GET /users/42 one user
GET /users/42/orders that user's orders
POST /orders create an order
PATCH /orders/7 change part of order 7
DELETE /orders/7/items/3 remove one item
তিনটা দেখার পরেই বাকিগুলো আন্দাজ করতে পারবে। এটাই REST এর মূল idea: তোমার data কে URL সহ resource হিসেবে নাম দাও, আর তার উপর কাজ করো HTTP এর standard method (lesson 4) আর status code (lesson 5) দিয়ে। এটা কোনো library বা protocol না। এটা API design করার একটা উপায়, যাতে client, cache আর team এর নতুন মানুষের কাছে সবকিছু predictable থাকে।
The problem: every action invents its own rules
| Client এর প্রশ্ন | Action-style API (HTTP এর উপর RPC) | Resource-style API (REST) |
|---|---|---|
| URL কী? | প্রতিটা action এর জন্য খুঁজে দেখো | Noun থেকে আন্দাজ করো: /orders/7 |
| কোন method? | প্রায়ই সবকিছুতে POST | GET পড়ে, POST বানায়, PATCH/PUT update করে, DELETE মুছে ফেলে |
| কাজ হলো কিনা? | মাঝে মাঝে 200 {"success": false} | Status code: 201, 404, 409, 422... |
| Cache বা proxy কি কাজে আসবে? | কোনটা safe কেউ জানে না | GET definition অনুযায়ীই safe আর cacheable |
| Retry করা safe? | Depend করে, docs পড়ো | PUT আর DELETE idempotent (পরের lesson) |
HTTP যা আগে থেকেই define করে রেখেছে, API সেটা যত বেশি reuse করে, প্রতিটা client কে তত কম শিখতে হয়। আর আগে থেকে থাকা জিনিসগুলো (browser, cache, proxy, retry library) তত বেশি কাজ free তে করে দেয়।
Think of a library
Library তে তুমি "ইতিহাসের বই আনার desk" বা "ধার নেওয়া উপন্যাস ফেরত দেওয়ার জানালা" তে যাও না। জিনিসের address থাকে: shelf 7, row 3, বই 12। আর address আছে এমন যেকোনো জিনিসের উপর অল্প কয়েকটা standard কাজ করা যায়: দেখা, ধার নেওয়া, ফেরত দেওয়া, নষ্ট হয়েছে বলে report করা।
- Address হলো URL:
/shelves/7/books/12। - Standard কাজ হলো HTTP method: GET, POST, PUT, PATCH, DELETE।
- নতুন বই এর জন্য নতুন desk লাগে না। শুধু নতুন address পায়।
Analogy টা কোথায় খাটে না। Library এর বই একটা physical জিনিস। কিন্তু REST resource হলো data এর একটা representation। সেই data কয়েকটা table এ থাকতে পারে, তখনই compute হতে পারে, বা এক client এর জন্য JSON আর আরেকজনের জন্য CSV হয়ে আসতে পারে। URL জিনিসটার নাম দেয়, storage এর না।
The building blocks
- Resource হলো noun। User, order, invoice, review। Process ও resource হতে পারে: password reset হলো
POST /password-resets, একটা payment এর চেষ্টা হলোPOST /payments। - Collection আর item।
/ordersহলো collection,/orders/7তার ভেতরের একটা item। সবসময় plural noun use করো। - Verb বহন করে method।
GET /orderslist দেয়,POST /ordersবানায়,GET /orders/7পড়ে,PUT /orders/7পুরোটা replace করে,PATCH /orders/7কিছু field বদলায়,DELETE /orders/7মুছে ফেলে। URL এ কখনোget,createবাdeleteলেখা থাকে না। - Nesting দেখায় কে কার মালিক, এক দুই level পর্যন্ত।
/books/2/reviewsস্বাভাবিকভাবে পড়া যায়: book 2 এর review গুলো।/users/1/orders/7/items/3/notesএর মতো লম্বা chain সহজেই ভাঙে। Child এর নিজের id থাকলে সেটা নিজের top-level URL এও থাকতে পারে (/items/3)। - Status code বলে কী হলো।
201 Created, সাথে নতুন resource এর দিকে point করাLocationheader। Delete এর পর204 No Content। Resource না থাকলে404। Method খাটে না এমন হলে405 Method Not Allowed, সাথেAllowheader। Conflict হলে409, data invalid হলে422। - Representation, table না। তুমি যে JSON ফেরত দাও, সেটা client এর জন্য design করা একটা view। Database এ আছে বলেই column এর নাম, internal flag বা join table বাইরে দিয়ে দিও না।
- Statelessness। প্রতিটা request এ handle করার জন্য যা যা লাগে সব থাকে (auth token, id, parameter)। দুই request এর মাঝে server "এখনকার order" মনে রাখে না (Module 1, lesson 5)। এজন্যই load balancer এর পেছনের যেকোনো server যেকোনো request handle করতে পারে।
- সবকিছু খাপ খায় না, তাতে সমস্যা নেই। "এই invoice টা email এ পাঠাও" একটা action। সাধারণ উপায় দুইটা: এটাকে resource বানাও (
POST /invoices/7/emails), অথবা পরিষ্কার নামের একটা action sub-path রাখো (POST /invoices/7:sendবা/invoices/7/send)। যেটাই নাও, পুরো API তে একটা style রাখো।
Order 7 cancel করার সবচেয়ে RESTful উপায় কোনটা, যদি cancel হওয়া order পরেও থাকে আর দেখা যায়?
Behind the scenes: creating a review
POST /books/2/reviews, route থেকে response পর্যন্ত
ধাপ 1/5 Request একটা resource এর নাম বলে
POST /books/2/reviews, body {"stars":5}। URL বলে কোন collection, method বলে এর ভেতরে কিছু বানাও।
- method
- POST
- collection
- /books/2/reviews
The picture to keep in your head
একটা REST API হলো address এর একটা map, সাথে ছোট আর fixed কয়েকটা verb।
- Address (URL) জিনিসের নাম দেয়: collection আর item, nested শুধু যেখানে মালিকানা আসল।
- Verb (method) সব জায়গায় একই: GET, POST, PUT, PATCH, DELETE।
- উত্তর (status code) সব জায়গায় একই: 200, 201, 204, 404, 405, 409, 422।
- একটা resource শিখলে পরেরটা আন্দাজ করতে পারবে। ভালো design এর test এটাই।
Try it: is this a good resource design?
ভালো URL, নাকি action URL?
the orders of user 42
Code from first principles
কোনো web framework ছাড়া ছোট্ট একটা REST engine। Path কে segment এ ভাগ করে। Segment বিজোড় সংখ্যক হলে collection, জোড় হলে একটা item। Parent আছে কিনা check করে, আর কী করবে সেটা method দেখে ঠিক করে। কোনো URL এ কোনো verb নেই। Request body আগেই decode হয়ে আসে (JSON decode করা ছিল lesson 7 এ)।
package main
import (
"fmt"
"strconv"
"strings"
)
// A field is a name and its value already written as JSON ("\"Dune\"" or "5").
type field struct{ k, v string }
type record struct {
id int
fields []field
}
// Every collection lives at its own path: "/books", "/books/2/reviews", ...
var store = map[string][]*record{}
var nextID = map[string]int{}
// children says which collections may hang under which: a book has reviews.
var children = map[string]string{"": "books", "books": "reviews"}
func obj(id int, fs []field) string {
parts := []string{}
if id > 0 {
parts = append(parts, `"id":`+strconv.Itoa(id))
}
for _, f := range fs {
parts = append(parts, `"`+f.k+`":`+f.v)
}
return "{" + strings.Join(parts, ",") + "}"
}
func find(coll string, id int) *record {
for _, r := range store[coll] {
if r.id == id {
return r
}
}
return nil
}
func notFound(p string) string { return `404, {"error":"not found: ` + p + `"}` }
// handle maps (method, resource path) to an action. Odd number of segments = a collection,
// even = one item in it. Nothing in the URL is a verb; the method says what to do.
func handle(method, path string, body []field) string {
segs := strings.Split(strings.Trim(path, "/"), "/")
parent := ""
for i := 0; i < len(segs); i += 2 { // walk /books/2/reviews/1 pair by pair
if children[parent] != segs[i] {
return notFound("/" + strings.Join(segs[:i+1], "/"))
}
if i+1 < len(segs) && i+2 < len(segs) { // an id in the middle must exist
id, err := strconv.Atoi(segs[i+1])
coll := "/" + strings.Join(segs[:i+1], "/")
if err != nil || find(coll, id) == nil {
return notFound(coll + "/" + segs[i+1])
}
}
parent = segs[i]
}
if len(segs)%2 == 1 { // a collection
coll := "/" + strings.Join(segs, "/")
switch method {
case "GET":
items := []string{}
for _, r := range store[coll] {
items = append(items, obj(r.id, r.fields))
}
return "200, [" + strings.Join(items, ",") + "]"
case "POST":
nextID[coll]++
r := &record{nextID[coll], body}
store[coll] = append(store[coll], r)
return fmt.Sprintf("201, Location: %s/%d, %s", coll, r.id, obj(r.id, r.fields))
}
return "405, Allow: GET, POST"
}
coll := "/" + strings.Join(segs[:len(segs)-1], "/")
id, err := strconv.Atoi(segs[len(segs)-1])
r := find(coll, id)
if err != nil || r == nil {
return notFound(path)
}
switch method {
case "GET":
return "200, " + obj(r.id, r.fields)
case "PATCH": // change only the fields that were sent
for _, nf := range body {
for i := range r.fields {
if r.fields[i].k == nf.k {
r.fields[i].v = nf.v
}
}
}
return "200, " + obj(r.id, r.fields)
case "DELETE":
list := store[coll][:0]
for _, x := range store[coll] {
if x.id != id {
list = append(list, x)
}
}
store[coll] = list
delete(store, path+"/reviews") // its children go with it
return "204"
}
return "405, Allow: GET, PATCH, DELETE"
}
func main() {
reqs := []struct {
method, path string
body []field
}{
{"POST", "/books", []field{{"title", `"Dune"`}}},
{"POST", "/books", []field{{"title", `"Emma"`}}},
{"GET", "/books", nil},
{"GET", "/books/2", nil},
{"POST", "/books/2/reviews", []field{{"stars", "5"}}},
{"GET", "/books/2/reviews", nil},
{"PATCH", "/books/1", []field{{"title", `"Dune Messiah"`}}},
{"DELETE", "/books/1", nil},
{"GET", "/books/1", nil},
{"POST", "/books/9/reviews", []field{{"stars", "1"}}},
{"PUT", "/books", nil},
{"GET", "/authors", nil},
}
for _, q := range reqs {
label := q.method + " " + q.path
if q.body != nil {
label += " " + obj(0, q.body)
}
fmt.Printf("%-40s -> %s\n", label, handle(q.method, q.path, q.body))
}
}// A field is [name, value already written as JSON] ('"Dune"' or "5").
// Every collection lives at its own path: "/books", "/books/2/reviews", ...
const store = new Map();
const nextID = new Map();
// children says which collections may hang under which: a book has reviews.
const children = { "": "books", books: "reviews" };
function obj(id, fs) {
const parts = [];
if (id > 0) parts.push(`"id":${id}`);
for (const [k, v] of fs) parts.push(`"${k}":${v}`);
return "{" + parts.join(",") + "}";
}
const find = (coll, id) => (store.get(coll) || []).find((r) => r.id === id);
const notFound = (p) => `404, {"error":"not found: ${p}"}`;
const toId = (s) => (/^\d+$/.test(s) ? Number(s) : NaN);
// handle maps (method, resource path) to an action. Odd number of segments = a collection,
// even = one item in it. Nothing in the URL is a verb; the method says what to do.
function handle(method, path, body) {
const segs = path.replace(/^\/|\/$/g, "").split("/");
let parent = "";
for (let i = 0; i < segs.length; i += 2) { // walk /books/2/reviews/1 pair by pair
if (children[parent] !== segs[i]) return notFound("/" + segs.slice(0, i + 1).join("/"));
if (i + 2 < segs.length) { // an id in the middle must exist
const coll = "/" + segs.slice(0, i + 1).join("/");
if (!find(coll, toId(segs[i + 1]))) return notFound(coll + "/" + segs[i + 1]);
}
parent = segs[i];
}
if (segs.length % 2 === 1) { // a collection
const coll = "/" + segs.join("/");
if (method === "GET") return "200, [" + (store.get(coll) || []).map((r) => obj(r.id, r.fields)).join(",") + "]";
if (method === "POST") {
nextID.set(coll, (nextID.get(coll) || 0) + 1);
const r = { id: nextID.get(coll), fields: body };
store.set(coll, [...(store.get(coll) || []), r]);
return `201, Location: ${coll}/${r.id}, ${obj(r.id, r.fields)}`;
}
return "405, Allow: GET, POST";
}
const coll = "/" + segs.slice(0, -1).join("/");
const id = toId(segs.at(-1));
const r = find(coll, id);
if (!r) return notFound(path);
if (method === "GET") return "200, " + obj(r.id, r.fields);
if (method === "PATCH") { // change only the fields that were sent
for (const [k, v] of body) for (const f of r.fields) if (f[0] === k) f[1] = v;
return "200, " + obj(r.id, r.fields);
}
if (method === "DELETE") {
store.set(coll, store.get(coll).filter((x) => x.id !== id));
store.delete(path + "/reviews"); // its children go with it
return "204";
}
return "405, Allow: GET, PATCH, DELETE";
}
const reqs = [
["POST", "/books", [["title", '"Dune"']]],
["POST", "/books", [["title", '"Emma"']]],
["GET", "/books", null],
["GET", "/books/2", null],
["POST", "/books/2/reviews", [["stars", "5"]]],
["GET", "/books/2/reviews", null],
["PATCH", "/books/1", [["title", '"Dune Messiah"']]],
["DELETE", "/books/1", null],
["GET", "/books/1", null],
["POST", "/books/9/reviews", [["stars", "1"]]],
["PUT", "/books", null],
["GET", "/authors", null],
];
for (const [method, path, body] of reqs) {
let label = method + " " + path;
if (body) label += " " + obj(0, body);
console.log(`${label.padEnd(40)} -> ${handle(method, path, body)}`);
}use std::collections::HashMap;
// A field is a name and its value already written as JSON ("\"Dune\"" or "5").
type Field = (String, String);
struct Record {
id: u32,
fields: Vec<Field>,
}
struct Api {
// Every collection lives at its own path: "/books", "/books/2/reviews", ...
store: HashMap<String, Vec<Record>>,
next_id: HashMap<String, u32>,
}
// children says which collections may hang under which: a book has reviews.
fn child_of(parent: &str) -> &str {
match parent {
"" => "books",
"books" => "reviews",
_ => "",
}
}
fn obj(id: u32, fs: &[Field]) -> String {
let mut parts = Vec::new();
if id > 0 {
parts.push(format!("\"id\":{}", id));
}
for (k, v) in fs {
parts.push(format!("\"{}\":{}", k, v));
}
format!("{{{}}}", parts.join(","))
}
fn not_found(p: &str) -> String {
format!("404, {{\"error\":\"not found: {}\"}}", p)
}
impl Api {
fn exists(&self, coll: &str, id: Option<u32>) -> bool {
match (self.store.get(coll), id) {
(Some(list), Some(id)) => list.iter().any(|r| r.id == id),
_ => false,
}
}
// handle maps (method, resource path) to an action. Odd number of segments = a collection,
// even = one item in it. Nothing in the URL is a verb; the method says what to do.
fn handle(&mut self, method: &str, path: &str, body: Option<&[Field]>) -> String {
let segs: Vec<&str> = path.trim_matches('/').split('/').collect();
let mut parent = "";
let mut i = 0;
while i < segs.len() {
// walk /books/2/reviews/1 pair by pair
if child_of(parent) != segs[i] {
return not_found(&format!("/{}", segs[..=i].join("/")));
}
if i + 2 < segs.len() {
// an id in the middle must exist
let coll = format!("/{}", segs[..=i].join("/"));
if !self.exists(&coll, segs[i + 1].parse().ok()) {
return not_found(&format!("{}/{}", coll, segs[i + 1]));
}
}
parent = segs[i];
i += 2;
}
if segs.len() % 2 == 1 {
// a collection
let coll = format!("/{}", segs.join("/"));
return match method {
"GET" => {
let items: Vec<String> = self.store.get(&coll).map_or(vec![], |l| l.iter().map(|r| obj(r.id, &r.fields)).collect());
format!("200, [{}]", items.join(","))
}
"POST" => {
let id = self.next_id.entry(coll.clone()).or_insert(0);
*id += 1;
let r = Record { id: *id, fields: body.unwrap().to_vec() };
let out = format!("201, Location: {}/{}, {}", coll, r.id, obj(r.id, &r.fields));
self.store.entry(coll).or_default().push(r);
out
}
_ => "405, Allow: GET, POST".to_string(),
};
}
let coll = format!("/{}", segs[..segs.len() - 1].join("/"));
let id: Option<u32> = segs[segs.len() - 1].parse().ok();
if !self.exists(&coll, id) {
return not_found(path);
}
let id = id.unwrap();
let list = self.store.get_mut(&coll).unwrap();
match method {
"GET" => {
let r = list.iter().find(|r| r.id == id).unwrap();
format!("200, {}", obj(r.id, &r.fields))
}
"PATCH" => {
// change only the fields that were sent
let r = list.iter_mut().find(|r| r.id == id).unwrap();
for (k, v) in body.unwrap() {
for f in r.fields.iter_mut() {
if &f.0 == k {
f.1 = v.clone();
}
}
}
format!("200, {}", obj(r.id, &r.fields))
}
"DELETE" => {
list.retain(|x| x.id != id);
self.store.remove(&format!("{}/reviews", path)); // its children go with it
"204".to_string()
}
_ => "405, Allow: GET, PATCH, DELETE".to_string(),
}
}
}
fn f(k: &str, v: &str) -> Vec<Field> {
vec![(k.to_string(), v.to_string())]
}
fn main() {
let mut api = Api { store: HashMap::new(), next_id: HashMap::new() };
let reqs: Vec<(&str, &str, Option<Vec<Field>>)> = vec![
("POST", "/books", Some(f("title", "\"Dune\""))),
("POST", "/books", Some(f("title", "\"Emma\""))),
("GET", "/books", None),
("GET", "/books/2", None),
("POST", "/books/2/reviews", Some(f("stars", "5"))),
("GET", "/books/2/reviews", None),
("PATCH", "/books/1", Some(f("title", "\"Dune Messiah\""))),
("DELETE", "/books/1", None),
("GET", "/books/1", None),
("POST", "/books/9/reviews", Some(f("stars", "1"))),
("PUT", "/books", None),
("GET", "/authors", None),
];
for (method, path, body) in &reqs {
let mut label = format!("{} {}", method, path);
if let Some(b) = body {
label += &format!(" {}", obj(0, b));
}
println!("{:<40} -> {}", label, api.handle(method, path, body.as_deref()));
}
}# A field is [name, value already written as JSON] ('"Dune"' or "5").
# Every collection lives at its own path: "/books", "/books/2/reviews", ...
store = {}
next_id = {}
# children says which collections may hang under which: a book has reviews.
children = {"": "books", "books": "reviews"}
def obj(id, fs):
parts = [f'"id":{id}'] if id > 0 else []
parts += [f'"{k}":{v}' for k, v in fs]
return "{" + ",".join(parts) + "}"
def find(coll, id):
return next((r for r in store.get(coll, []) if r["id"] == id), None)
def not_found(p):
return f'404, {{"error":"not found: {p}"}}'
def to_id(s):
return int(s) if s.isdigit() else None
def handle(method, path, body):
"""Map (method, resource path) to an action. Odd number of segments = a collection,
even = one item in it. Nothing in the URL is a verb; the method says what to do."""
segs = path.strip("/").split("/")
parent = ""
for i in range(0, len(segs), 2): # walk /books/2/reviews/1 pair by pair
if children.get(parent) != segs[i]:
return not_found("/" + "/".join(segs[: i + 1]))
if i + 2 < len(segs): # an id in the middle must exist
coll = "/" + "/".join(segs[: i + 1])
if find(coll, to_id(segs[i + 1])) is None:
return not_found(coll + "/" + segs[i + 1])
parent = segs[i]
if len(segs) % 2 == 1: # a collection
coll = "/" + "/".join(segs)
if method == "GET":
return "200, [" + ",".join(obj(r["id"], r["fields"]) for r in store.get(coll, [])) + "]"
if method == "POST":
next_id[coll] = next_id.get(coll, 0) + 1
r = {"id": next_id[coll], "fields": body}
store.setdefault(coll, []).append(r)
return f"201, Location: {coll}/{r['id']}, {obj(r['id'], r['fields'])}"
return "405, Allow: GET, POST"
coll = "/" + "/".join(segs[:-1])
id = to_id(segs[-1])
r = find(coll, id)
if r is None:
return not_found(path)
if method == "GET":
return "200, " + obj(r["id"], r["fields"])
if method == "PATCH": # change only the fields that were sent
for k, v in body:
for f in r["fields"]:
if f[0] == k:
f[1] = v
return "200, " + obj(r["id"], r["fields"])
if method == "DELETE":
store[coll] = [x for x in store[coll] if x["id"] != id]
store.pop(path + "/reviews", None) # its children go with it
return "204"
return "405, Allow: GET, PATCH, DELETE"
reqs = [
("POST", "/books", [["title", '"Dune"']]),
("POST", "/books", [["title", '"Emma"']]),
("GET", "/books", None),
("GET", "/books/2", None),
("POST", "/books/2/reviews", [["stars", "5"]]),
("GET", "/books/2/reviews", None),
("PATCH", "/books/1", [["title", '"Dune Messiah"']]),
("DELETE", "/books/1", None),
("GET", "/books/1", None),
("POST", "/books/9/reviews", [["stars", "1"]]),
("PUT", "/books", None),
("GET", "/authors", None),
]
for method, path, body in reqs:
label = f"{method} {path}"
if body is not None:
label += " " + obj(0, body)
print(f"{label:<40} -> {handle(method, path, body)}")import java.util.*;
public class Main {
// A field is {name, value already written as JSON} ("\"Dune\"" or "5").
static class Rec {
int id;
List<String[]> fields;
Rec(int id, List<String[]> fields) { this.id = id; this.fields = fields; }
}
// Every collection lives at its own path: "/books", "/books/2/reviews", ...
static Map<String, List<Rec>> store = new HashMap<>();
static Map<String, Integer> nextId = new HashMap<>();
// children says which collections may hang under which: a book has reviews.
static Map<String, String> children = Map.of("", "books", "books", "reviews");
static String obj(int id, List<String[]> fs) {
List<String> parts = new ArrayList<>();
if (id > 0) parts.add("\"id\":" + id);
for (String[] f : fs) parts.add("\"" + f[0] + "\":" + f[1]);
return "{" + String.join(",", parts) + "}";
}
static Rec find(String coll, String idText) {
if (!idText.matches("\\d+")) return null;
int id = Integer.parseInt(idText);
for (Rec r : store.getOrDefault(coll, List.of())) if (r.id == id) return r;
return null;
}
static String notFound(String p) { return "404, {\"error\":\"not found: " + p + "\"}"; }
static String join(String[] segs, int from, int to) {
return "/" + String.join("/", Arrays.copyOfRange(segs, from, to));
}
// handle maps (method, resource path) to an action. Odd number of segments = a collection,
// even = one item in it. Nothing in the URL is a verb; the method says what to do.
static String handle(String method, String path, List<String[]> body) {
String[] segs = path.replaceAll("^/|/$", "").split("/");
String parent = "";
for (int i = 0; i < segs.length; i += 2) { // walk /books/2/reviews/1 pair by pair
if (!segs[i].equals(children.get(parent))) return notFound(join(segs, 0, i + 1));
if (i + 2 < segs.length) { // an id in the middle must exist
String coll = join(segs, 0, i + 1);
if (find(coll, segs[i + 1]) == null) return notFound(coll + "/" + segs[i + 1]);
}
parent = segs[i];
}
if (segs.length % 2 == 1) { // a collection
String coll = join(segs, 0, segs.length);
if (method.equals("GET")) {
List<String> items = new ArrayList<>();
for (Rec r : store.getOrDefault(coll, List.of())) items.add(obj(r.id, r.fields));
return "200, [" + String.join(",", items) + "]";
}
if (method.equals("POST")) {
int id = nextId.merge(coll, 1, Integer::sum);
Rec r = new Rec(id, body);
store.computeIfAbsent(coll, k -> new ArrayList<>()).add(r);
return "201, Location: " + coll + "/" + id + ", " + obj(id, r.fields);
}
return "405, Allow: GET, POST";
}
String coll = join(segs, 0, segs.length - 1);
Rec r = find(coll, segs[segs.length - 1]);
if (r == null) return notFound(path);
switch (method) {
case "GET":
return "200, " + obj(r.id, r.fields);
case "PATCH": // change only the fields that were sent
for (String[] nf : body) for (String[] f : r.fields) if (f[0].equals(nf[0])) f[1] = nf[1];
return "200, " + obj(r.id, r.fields);
case "DELETE":
store.get(coll).removeIf(x -> x.id == r.id);
store.remove(path + "/reviews"); // its children go with it
return "204";
}
return "405, Allow: GET, PATCH, DELETE";
}
static List<String[]> f(String k, String v) {
List<String[]> l = new ArrayList<>();
l.add(new String[]{k, v});
return l;
}
public static void main(String[] args) {
Object[][] reqs = {
{"POST", "/books", f("title", "\"Dune\"")},
{"POST", "/books", f("title", "\"Emma\"")},
{"GET", "/books", null},
{"GET", "/books/2", null},
{"POST", "/books/2/reviews", f("stars", "5")},
{"GET", "/books/2/reviews", null},
{"PATCH", "/books/1", f("title", "\"Dune Messiah\"")},
{"DELETE", "/books/1", null},
{"GET", "/books/1", null},
{"POST", "/books/9/reviews", f("stars", "1")},
{"PUT", "/books", null},
{"GET", "/authors", null},
};
for (Object[] q : reqs) {
String method = (String) q[0], path = (String) q[1];
@SuppressWarnings("unchecked")
List<String[]> body = (List<String[]>) q[2];
String label = method + " " + path + (body != null ? " " + obj(0, body) : "");
System.out.printf("%-40s -> %s%n", label, handle(method, path, body));
}
}
}Output (পাঁচটা language এই একই):
POST /books {"title":"Dune"} -> 201, Location: /books/1, {"id":1,"title":"Dune"}
POST /books {"title":"Emma"} -> 201, Location: /books/2, {"id":2,"title":"Emma"}
GET /books -> 200, [{"id":1,"title":"Dune"},{"id":2,"title":"Emma"}]
GET /books/2 -> 200, {"id":2,"title":"Emma"}
POST /books/2/reviews {"stars":5} -> 201, Location: /books/2/reviews/1, {"id":1,"stars":5}
GET /books/2/reviews -> 200, [{"id":1,"stars":5}]
PATCH /books/1 {"title":"Dune Messiah"} -> 200, {"id":1,"title":"Dune Messiah"}
DELETE /books/1 -> 204
GET /books/1 -> 404, {"error":"not found: /books/1"}
POST /books/9/reviews {"stars":1} -> 404, {"error":"not found: /books/9"}
PUT /books -> 405, Allow: GET, POST
GET /authors -> 404, {"error":"not found: /authors"}
Output টা পড়ি:
- Create করলে
201আর একটাLocationআসে:/books/1,/books/2, তারপর/books/2/reviews/1। Client নতুন URL টা response থেকে জানে। id আন্দাজ করে নিজে URL বানায় না। - একই দুইটা URL shape দিয়ে সব কাজ:
/booksআর/books/2দিয়ে list, create, read, change আর delete হয়েছে। Nested/books/2/reviewsহুবহু একই code reuse করেছে। PATCHশুধু title বদলেছে, আর update হওয়া representation ফেরত দিয়েছে।DELETEদিয়েছে204, আর পরেরGET /books/1হলো404: resource টা আর নেই।- Error দেখায় কোনটা নেই: book 9 এর review fail করেছে
not found: /books/9দিয়ে, মানে parent টা নেই। "review not found" এর মতো confusing কিছু না। PUT /booksহলো405, সাথেAllow: GET, POST: resource আছে, কিন্তু method টা খাটে না, আর response বলে দেয় কোনগুলো খাটে।
এবার একটা আসল public practice API তে একই shape, jsonplaceholder:
$ B=https://jsonplaceholder.typicode.com
$ for p in /posts/1 /posts/1/comments /users/1/posts /posts/9999; do curl -s -o /dev/null -w "GET $p -> %{http_code}\n" $B$p; done
GET /posts/1 -> 200
GET /posts/1/comments -> 200
GET /users/1/posts -> 200
GET /posts/9999 -> 404
$ curl -s $B/posts/1/comments | jq "length, .[0].postId"
5
1
$ curl -s -X POST $B/posts -H "Content-Type: application/json" -d '{"title":"Dune","userId":1}' -w "\nstatus %{http_code}\n"
{
"title": "Dune",
"userId": 1,
"id": 101
}
status 201
/posts/1/commentsআর/users/1/posts: nested collection, ঠিক/books/2/reviewsএর মতো। Docs ছাড়াই দুইটা URL আন্দাজ করতে পারতে।/posts/9999হলো404: এমন resource যেটা নেই।- Collection এ POST করলে
201আসে, সাথে id সহ নতুন item (এই practice API save টা fake করে, তাই সবসময় 101 বলে)।
Real engineering
- আগে resource এর list লেখো। কোনো code এর আগে noun গুলো, তাদের URL, প্রতিটা কোন method support করে আর কী ফেরত দেয়, সেটা লিখে ফেলো। Design ঠিক করার সবচেয়ে সস্তা সময় এটাই।
- একঘেয়ে রকমের consistent থাকো: plural noun, ছোট হাতের অক্ষর আর hyphen (
/password-resets), একই id format, একই field naming (created_atবাcreatedAt, দুইটা না), সব জায়গায় একটাই error format (যেমন RFC 9457 problem details:{"type","title","status","detail"})। - OpenAPI দিয়ে describe করো। Machine-readable একটা spec থেকে একটা file দিয়েই docs, client SDK, mock server আর contract test পাওয়া যায়।
- Create এ
Locationআর update এ পুরো representation ফেরত দাও, যাতে result দেখতে client কে দ্বিতীয় request করতে না হয়। - Collection এ filter, sort আর page করো query parameter দিয়ে:
GET /orders?status=paid&sort=-created_at&limit=20(lesson 14)।/getPaidOrdersএর মতো নতুন endpoint বানিও না। - কখন REST সবচেয়ে ভালো fit না, সেটা জানো। একটা screen এর জন্য অনেকগুলো ছোট related read লাগলে GraphQL ভালো হতে পারে। বেশি throughput এর service-to-service call এ প্রায়ই gRPC use হয়। Public আর web API এর জন্য REST default, কারণ সব tool HTTP বোঝে।
When it breaks
একটা failure বেছে নাও
POST /sendWelcomeEmail retried by the client library
Think before you read on
একটা shop এমন একটা endpoint চায় যেটা cart "checkout" করবে: একটা order বানাবে, card charge করবে, আর cart খালি করবে। এটা পরিষ্কারভাবেই একটা action। এটাকে resource হিসেবে কীভাবে model করবে, আর তাতে লাভ কী?
Reveal
ফলাফলটাকেই resource বানাও: POST /orders, body {"cart_id": 55} (অথবা POST /checkouts)। এটা ফেরত দেয় 201 Created, সাথে Location: /orders/901। লাভ হলো: ফলাফলের একটা address থাকলো। Payment সফল হয়েছে কিনা দেখতে client GET /orders/901 করতে পারে। Order আগেই তৈরি হয়েছে কিনা check করে safely retry করতে পারে। আর support পরে এটা খুঁজে দেখতে পারে। শুধু POST /checkout action হলে, payment এর মাঝপথে response হারিয়ে গেলে দেখার মতো কিছুই থাকে না।
Check yourself
1. REST এ একটা কাজের verb কোথায় থাকে?
Answer
HTTP method এ (GET, POST, PUT, PATCH, DELETE)। URL noun দিয়ে resource এর নাম দেয়।
2. সফল create এ কী ফেরত দেওয়া উচিত?
Answer
201 Created, নতুন resource এর URL সহ একটা Location header, আর সাধারণত body তে নতুন representation।
3. GET কেন কখনো data বদলাবে না?
Answer
GET কে safe হিসেবে define করা হয়েছে। Browser এটা prefetch করে, crawler follow করে, cache আবার চালায়, আর client ইচ্ছামতো retry করে। GET এর পেছনে কোনো state বদল থাকলে সেটা ভুল করেই trigger হবে।
4. কখন 404 এর চেয়ে 405 Method Not Allowed বেশি ঠিক?
Answer
যখন resource আছে কিন্তু ওই method support করে না, যেমন একটা collection এ PUT /books। Response এ একটা Allow header থাকা উচিত, যেটা কাজ করে এমন method গুলোর list দেয়।
Your challenge: add PUT
Engine এ item এর জন্য PUT যোগ করো:
- পুরো body সহ
PUT /books/2record টা replace করে: যে field পাঠানো হয়নি, সেগুলো মুছে যায়। - Item না থাকলে
404দাও (কিছু APIPUTদিয়ে বানিয়ে ফেলে; একটা বেছে নাও আর consistent থাকো)। - Item এর
Allowheader বদলে করোGET, PUT, PATCH, DELETE। - পাঠাও
PATCH /books/2 {"year":1815}, তারপরPUT /books/2 {"title":"Emma"}, তারপরGET /books/2।
Run করার আগে predict করো: শেষ GET কী ফেরত দেবে, আর শেষ ধাপটা PATCH হলে কী দিতো?
তুমি সফল যখন শেষ GET /books/2 ফেরত দেবে {"id":2,"title":"Emma"}, কোনো year ছাড়া, আর ওই PUT কে PATCH করলে year field থেকে যাবে।
Hint: শুরুর code এ PATCH শুধু আগে থেকে থাকা field বদলায়। তাই year এর ধাপের জন্য PATCH কে নতুন field যোগ করতেও দাও।
The mental model
REST তোমার data কে URL সহ resource হিসেবে নাম দেয় (plural noun, collection আর item, nested শুধু যেখানে মালিকানা আসল), আর HTTP এর fixed verb আর status code দিয়ে তার উপর কাজ করে। GET safe, POST বানায় (201 + Location), PUT replace করে, PATCH একটা অংশ বদলায়, DELETE মুছে ফেলে (204); 404 মানে এমন resource নেই, 405 মানে এমন method নেই। Table না, representation ফেরত দাও, প্রতিটা request কে self-contained রাখো, আর consistent থাকো, যাতে একটা resource দেখা client বাকিগুলো আন্দাজ করতে পারে।
Station stamp
Chapter শেষ করো
পড়া শেষ হলে Complete চাপো, progress save হবে। XP শুধু Pro তে — Pro থাকলে এই chapter এ +10 XP পেতে।
Pro নিয়ে XP পাও →