Since the CRUD API lesson, the Bookshop books have lived in an array. That array lives in the server's memory, so when the server restarts (stops and starts again), any newly added book is gone. A real API keeps its data in a database. Every request then asks the database for data with a query: a command written in the SQL language.
Take the Bookshop storeroom. Customers (the clients) aren't allowed in. The shop assistant (the API) gives a slip to the storekeeper (the database): "fetch the book titled [ ______ ]". The storekeeper reads whatever is in that box as a title, then brings the book that matches. In the code, the slip is the query, and its empty box is called a placeholder.
The books table in the database
From this lesson on, the Bookshop books live in a SQLite table called books, with 8 rows. SQLite is a small database kept in a single file. Each row of the table is one book, and each column is one kind of data, such as price. The authors' names are in the authors table. Making tables and writing SQL is covered in the SQL track. Here we focus on the API.
| id | title | author_id | price | stock | cost_price |
|---|---|---|---|---|---|
| 1 | The Rainbow Troops | 1 | 89000 | 12 | 61000 |
| 2 | This Earth of Mankind | 2 | 125000 | 0 | 90000 |
| 3 | Beauty Is a Wound | 3 | 110000 | 5 | 78000 |
| 4 | The Dancer | 4 | 95000 | 3 | 66000 |
| 5 | The Dreamer | 1 | 79000 | 8 | 55000 |
| 6 | Child of All Nations | 2 | 120000 | 2 | 86000 |
| 7 | Man Tiger | 3 | 98000 | 0 | 64000 |
| 8 | Edensor | 1 | 85000 | 6 | 52000 |
cost_price is what the shop paid for the book. That column is in the database, but the API never sends it.
Route, handler, query, response
A route is an endpoint registered in the code, such as app.get("/books", ...). Every request follows the same steps:
- The request reaches a route.
- The handler builds a query.
- The database answers with rows of data.
- The handler sends JSON.
Here it is for the list of books:
app.get("/books", (req, res) => {
const books = db
.prepare("SELECT id, title, author_id, price, stock FROM books")
.all();
res.json({ data: books, total: books.length });
});
dbis the connection to the database. It works like better-sqlite3, a SQLite library for Node.js. Opening the connection is covered in the Database Connection lesson of the Node.js track.db.prepare(sql)prepares one query..all()runs it and returns every row as an array of objects (one object per row).- The query in this code means "take the columns id, title, author_id, price and stock from the table
books". The columns are named one by one, notSELECT *(every column). WithSELECT *,cost_pricewould go out to everyone. { data: books, total: books.length }wraps the list indata, plus its count, as in the Pagination lesson. Heretotalis8.
This lesson uses better-sqlite3 because SQLite is only one file, with no database server, so it is easy to learn with. Real applications usually move to PostgreSQL or MySQL, databases that run as their own server. These are other options for calling a database from Node.js:
| Kind | Examples | When to pick it |
|---|---|---|
| Driver | better-sqlite3 and mysql2 (placeholder ?), pg for PostgreSQL (placeholders $1, $2) |
You want to write the SQL yourself. In pg, every query is waited for with await, for example through a pool (a set of connections): const { rows } = await pool.query("SELECT ... WHERE id = $1", [id]); |
| Query builder | Knex, Kysely | The query is built with functions, for example a filter that is sometimes there and sometimes not. |
| ORM | Prisma, Drizzle (in Laravel: Eloquent) | Tables are mapped to models, and the library also manages relations (links between tables) and migrations (changes to the table structure). |
One book: .get() and 404
For one book, the endpoint is:
app.get("/books/:id", (req, res) => {
const book = db
.prepare("SELECT id, title, author_id, price, stock FROM books WHERE id = ?")
.get(Number(req.params.id));
if (!book) {
return res.status(404).json({ error: "Book not found" });
}
res.json({ data: book });
});
?is a placeholder: an empty box in the SQL that a value fills, like the box on the storeroom slip. The value is passed to.get(...), separate from the SQL text.WHERE id = ?means "only the row whose id equals this value"..get()returns the first matching row, orundefinedwhen there is none.GET /books/2is answered200with This Earth of Mankind.GET /books/99getsundefined, so it's answered404.
Placeholders, not glued text
This is a title search endpoint, written two ways:
// DANGER: the client's input is glued into the SQL
const sql = "SELECT id, title FROM books WHERE title = '" + req.query.title + "'";
const found = db.prepare(sql).all();
// SAFE: the SQL text stays fixed, the value travels separately
const safe = db.prepare("SELECT id, title FROM books WHERE title = ?").all(req.query.title);
Say the client sends GET /books?title=x' OR '1'='1 to both versions. Before you look at the table, guess: with the first one, how many books come out? 0, 1, or all 8?
| Way | What reaches the database | Books that come out |
|---|---|---|
| Glued text | ... WHERE title = 'x' OR '1'='1' |
8, all of them |
| Placeholder | ... WHERE title = ? with the value x' OR '1'='1 |
0 |
In the first way, the quote in the input closes the title text in the SQL. Then OR '1'='1' becomes a new condition that is always true, so all 8 books come out. This is called SQL injection: the client's input turns into a command. With a placeholder, the database reads the value whole, as a title, just as the storekeeper reads what is in the slip's box. No book is titled x' OR '1'='1, so the result is 0. The full story is in the SQL Injection Prevention lesson of the Security track.
A placeholder can only fill in values: a title, a number, an id. Column names and the words ASC/DESC (ascending or descending order) can't go there. How to handle those is in the Filter & Sort lesson.
N+1: one query per row
The list page needs each book's author name. This is the way that looks reasonable:
const books = db.prepare("SELECT id, title, author_id FROM books").all();
for (const book of books) {
const author = db.prepare("SELECT name FROM authors WHERE id = ?").get(book.author_id);
book.author = author.name;
}
There is one query for the list, then one more query for each book: 1 + 8 = 9 queries. This is the N+1 problem (N = the number of rows). With 1,000 books it's 1,001 queries, and each one costs a round trip to the database. A JOIN, which combines two tables in one query, fetches everything at once:
const books = db.prepare(`
SELECT books.id, books.title, authors.name AS author
FROM books JOIN authors ON authors.id = books.author_id
`).all();
JOIN authors ON authors.id = books.author_id pairs each book with its author, and AS author gives the author's name column the name author. The result is one query, however many books there are. The details of N+1 are in the N+1 Problem & Eager Loading lesson of the Database track.
Don't fetch every row at once
A query with no limit is fine for 8 books. But if the table has 100,000 rows, for example a table of students, an endpoint with no limit loads 100,000 objects into the server's memory. It also sends about 10 MB of JSON on every request, if a row is roughly 100 bytes. The problem: no pagination. A list endpoint must always be limited, for example with LIMIT 20 OFFSET 0 in the SQL (take 20 rows, starting from the first row), as in the Pagination lesson.
📌 The Laravel version: Eloquent
In Laravel (the Laravel track), queries are written with Eloquent, Laravel's built-in ORM, which puts the placeholders in for you:
| better-sqlite3 | Eloquent |
|---|---|
db.prepare("SELECT * FROM students").all() |
Student::all() |
db.prepare("... WHERE id = ?").get(id) |
Student::find($id) |
| A JOIN for a relation | Student::with('classroom')->get() |
LIMIT 15 OFFSET 0 |
Student::paginate(15) |
Eloquent has the same N+1 trap:
$students = Student::all();
foreach ($students as $s) {
echo $s->classroom->name; // one more query for every student
}
Every $s->classroom runs a new query, so 100 students make 101 queries. Student::with('classroom')->get() (eager loading, loading the relation first) loads all the classes in one extra query, so 2 queries in total.
⚠️ Queries that leak, are slow, or fetch too much
- Gluing input into SQL.
"... WHERE title = '" + title + "'"opens the SQL injection hole, and so does a template literal`... '${title}'`. Use?and pass the value to.all(...)or.get(...). SELECT *on a public endpoint. Every column goes out,cost_priceorpassword_hashincluded. Name the columns one by one.- Forgetting the 404. A
.get()that finds no row returnsundefined, andres.json({ data: undefined })is answered200with{}. Check first, then answerres.status(404). - A query inside a loop. One query per row = N+1. Use a JOIN, or
with(...)in Laravel. - A list with no limit. 100,000 rows at once use up memory and bandwidth (network capacity). Use pagination.
TL;DR: A real API keeps its data in a database, and an endpoint asks for data with a query, a command in the SQL language. The steps: route, handler, query, response. db.prepare(sql).all() returns every row, and .get() returns one row or undefined (answer 404). A list is answered { data, total } with the columns named one by one, not SELECT *, so a column like cost_price (what the shop paid) doesn't go out. The client's input always goes through a ? placeholder (an empty box for a value), never glued into the SQL text. The title x' OR '1'='1 glued in brings out all 8 books (SQL injection), while through a placeholder 0 books come out. A query inside a loop is N+1 (1 + 8 = 9 queries). A JOIN (two tables combined in one query), or Student::with('classroom')->get() in Laravel, cuts it down. A big list needs pagination. In Eloquent, Student::all() fetches every row, so on 100,000 rows it is a problem.
⚡ One book: .get() and 404
Write:
app.get("/books/:id", (req, res) => {
const book = db
.prepare("SELECT id, title, author_id, price, stock FROM books WHERE id = ?")
.get(Number(req.params.id));
if (!book) {
return res.status(404).json({ error: "Book not found" });
}
res.json({ data: book });
});
Meaning: db is the connection to the database, and db.prepare prepares a query (an SQL command for the database). ? is a placeholder: an empty box filled with the value from .get(...), here the id from the URL. .get() returns the first matching row, or undefined when there is none, and that is answered 404. The columns are named one by one, so the cost_price column (what the shop paid), which is also in the table, never goes out.
⚡ Placeholders, not glued text
Write:
// SAFE: the SQL text stays fixed, the value travels separately
const safe = db.prepare("SELECT id, title FROM books WHERE title = ?").all(req.query.title);
Guess first: the title x' OR '1'='1 is glued straight into the SQL text of a title search. Out of 8 books, how many come out?
All 8. The quote in the input closes the title text in the SQL, and OR '1'='1' becomes a new condition that is always true. Through a placeholder, 0 books come out.
Meaning: Input that turns into an SQL command like this is called SQL injection. Through ? (a placeholder), the value is sent separately from the SQL text, so the database reads the value whole, as a title.
⚡ N+1: one query per row
Meaning: Fetching the list of books, then running one more query for each book's author, takes 1 + 8 = 9 queries for 8 books. This is the N+1 problem (N = the number of rows). One JOIN, which combines two tables in one query, fetches everything at once, however many books there are.
⚡ Don't fetch every row at once
Meaning: For a students table with 100,000 rows, an endpoint with no limit loads 100,000 objects into the server's memory. It also sends about 10 MB of JSON on every request. The problem: no pagination (splitting a list into pages). Limit the list, for example with LIMIT 20 OFFSET 0 (20 rows, starting from the first row).