Menampilkan data dari beberapa tabel yang berelasi di API response.
Nested resources:
GET /users/5/posts → Post milik user 5
GET /posts/3/comments → Komentar di post 3
app.get("/users/:userId/posts", (req, res) => {
const posts = db.prepare(
"SELECT * FROM posts WHERE user_id = ? ORDER BY created_at DESC"
).all(req.params.userId);
res.json({ data: posts });
});
Include related data (embedding):
app.get("/posts/:id", (req, res) => {
const post = db.prepare("SELECT * FROM posts WHERE id = ?").get(req.params.id);
if (!post) return res.status(404).json({ error: "Not found" });
// Include author info
const author = db.prepare("SELECT id, name, avatar FROM users WHERE id = ?").get(post.user_id);
// Include comments
const comments = db.prepare(
"SELECT c.*, u.name as author_name FROM comments c JOIN users u ON c.user_id = u.id WHERE c.post_id = ?"
).all(post.id);
res.json({
data: { ...post, author, comments }
});
});
Kapan embed vs separate endpoint:
- Embed: data yang hampir selalu dibutuhkan bersamaan
- Separate: data yang besar atau jarang dibutuhkan
- Optional:
?include=comments,authoruntuk client yang butuh