Your API works perfectly — until someone sends a request you didn't plan for. That's the moment most beginner tutorials abandon you. They show you how to build a route that returns a list of books, marvel at the JSON, and stop. They never show you what happens when the book doesn't exist, when the request body is empty, or when your "database" is just an array that resets every time the server restarts.
So let's fix that. This is a tutorial for building your first REST API, but the emphasis is on the parts that actually break in production: input validation, failure status codes, data persistence, and the small design decisions that separate a toy project from something you can hand to another developer without apologizing. We'll use Node.js and Express because that's the shortest path from zero to a running server, but every concept here transfers directly if you'd rather build a REST API in Python with FastAPI or Java with Spring Boot.
Key takeaways
- REST is a set of constraints, not a library. If your routes use nouns, HTTP verbs, and return the right status codes, you're doing REST.
- Validation and error handling are not "advanced" topics. Start them in your first hour, not your first month.
- An in-memory array is fine for learning — but the moment you close your laptop, your data dies. Persistence is a separate decision you make early.
- Status codes 400, 404, 409 and 422 are the ones beginners skip. They're also the ones that save you the most debugging pain.
- Version your routes from day one. Adding /v1/ costs five minutes and saves a migration later.
- Test with curl before you install a client. If you can't hit your endpoint from a terminal, the problem isn't your tool.
What a REST API actually is when you build your first one
Strip away the acronym and a REST API is a contract: a set of URLs that behave predictably when you hit them with a standard HTTP method. GET reads. POST creates. PUT or PATCH updates. DELETE removes. That's the vocabulary. The rest is discipline.
What makes it "RESTful" and not just "an API" comes down to a handful of constraints — statelessness (each request carries everything the server needs), a uniform interface (same shape of request every time), and resource-oriented URLs. That last one trips up nearly everyone. Your endpoint should be a thing, not an action:
- Good:
GET /books/42— retrieve one book - Bad:
GET /getBook?id=42— this is a function call wearing a URL as a costume
RESTful API vs REST API: is there a difference?
Practically, no. "REST API" and "RESTful API" describe the same thing, and people use the terms interchangeably in conversation, in job postings, and in documentation. The distinction, when anyone bothers to make it, is grammatical: "REST" is the architectural style, "RESTful" is the adjective for something that conforms to it. So an API that follows Roy Fielding's constraints is RESTful, and you can call it either.
What matters far more than the label is whether your API actually follows the constraints. Plenty of services call themselves RESTful while storing session state on the server, which breaks statelessness outright. Don't worry about winning that argument. Worry about whether your routes are consistent.
Setting up the project without drowning in configuration
You need three things: Node installed, an empty folder, and one dependency. That's genuinely it.
mkdir books-api
cd books-api
npm init -y
npm install express
Then create a file called server.js and put this in it:
const express = require('express');
const app = express();
app.use(express.json());
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Run it with node server.js. You now have a server that responds to nothing, which is a strange milestone but a real one. The express.json() line is the single most important thing on that page and the one beginners forget — without it, req.body is undefined on every POST request, and you'll spend an hour wondering why your data vanished.
One more thing before we write routes: install nodemon as a dev dependency (npm install --save-dev nodemon). It restarts the server every time you save a file. Without it you'll be pressing Ctrl+C and re-running manually roughly two hundred times today. I know because I did exactly that on my first API and it nearly killed my enthusiasm for the whole project.
Your first three routes, and what happens when they fail
Let's build a book collection. We'll start with an in-memory array and be honest with ourselves about its limitations.
let books = [
{ id: 1, title: 'The Pragmatic Programmer', author: 'Hunt & Thomas' },
{ id: 2, title: 'Refactoring', author: 'Martin Fowler' }
];
app.get('/v1/books', (req, res) => {
res.status(200).json(books);
});
That's the happy path, and it's where most tutorials stop. Now the interesting part.
Reading one resource — and the 404 you'll forget
app.get('/v1/books/:id', (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id)) {
return res.status(400).json({ error: 'ID must be an integer' });
}
const book = books.find(b => b.id === id);
if (!book) {
return res.status(404).json({ error: 'Book not found' });
}
res.status(200).json(book);
});
Two checks, two different status codes, and both matter. If someone hits /v1/books/abc, that's a malformed request — 400. If they hit /v1/books/999 and no such book exists, that's 404. Returning 404 for both cases is the mistake I made for weeks. It's the reason a frontend developer integrating with my API once spent an afternoon convinced his routing was broken, when actually my server was lying to him about what went wrong.
Creating a resource with real validation
app.post('/v1/books', (req, res) => {
const { title, author } = req.body || {};
if (!title || typeof title !== 'string' || !title.trim()) {
return res.status(422).json({ error: 'title is required' });
}
if (!author || typeof author !== 'string' || !author.trim()) {
return res.status(422).json({ error: 'author is required' });
}
const newBook = {
id: books.length ? Math.max(...books.map(b => b.id)) + 1 : 1,
title: title.trim(),
author: author.trim()
};
books.push(newBook);
res.status(201).json(newBook);
});
Note the 201 on success. It means "created," and it's the correct code — not 200. Also note the deliberate use of 422 for a well-formed request carrying invalid data, versus 400 for a request that isn't even parseable. Some teams use 400 for both, and that's defensible. Pick a convention and stay consistent across every endpoint; inconsistency is what actually confuses clients.
And the req.body || {} guard? That's there because a request with no body and no Content-Type header will give you undefined, and destructuring undefined throws. It's a two-second fix that prevents a 500 error, which brings me to the next point.
Handling errors globally instead of everywhere
Try/catch blocks in every route get ugly fast. Express has a cleaner pattern: an error-handling middleware with four arguments, registered last.
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Internal server error' });
});
Now any route that throws — a JSON parse failure, a bad database call, a typo in your code — lands here instead of dumping a stack trace to the client. Never send raw error messages to the client in production. They leak file paths and internal logic. Log them on the server, return something generic.
The table below sums up the status codes worth memorizing as a beginner. There are dozens more; these six cover the vast majority of what you'll write.
| Code | Meaning | When you return it |
|---|---|---|
| 200 | OK | Successful GET, PUT, PATCH, DELETE |
| 201 | Created | Successful POST that made a new resource |
| 400 | Bad Request | Malformed syntax, unparseable body or param |
| 404 | Not Found | The resource doesn't exist |
| 409 | Conflict | Duplicate — creating a book that already exists |
| 422 | Unprocessable Entity | Valid JSON, invalid data (missing title) |
Making your data survive a restart
Here's the hard truth about the array we've been using: it lives in memory, and memory dies when the process stops. Every restart, you're back to two books. Fine for a demo, useless for anything real.
The smallest possible step up is writing to a JSON file with Node's built-in fs module. It's not production-grade, and concurrent writes will eventually clobber each other, but it teaches the shape of persistence without adding a dependency.
The real answer, once you're past this tutorial, is a database. SQLite if you want zero setup and a single file. PostgreSQL if you're building something you intend to keep. Whichever you choose, the API layer barely changes — you swap the books.find(...) calls for queries. That separation is the point of structuring your routes this way, and it's why I'd argue strongly that you should learn to keep data access in its own function from the very beginning, even when the function just returns an array element. Retrofitting that separation later is tedious.
How to test your API before touching a client
Use curl first. If you can't reach your endpoint from a terminal, no GUI tool will magically fix it.
curl http://localhost:3000/v1/books
curl -X POST http://localhost:3000/v1/books \
-H "Content-Type: application/json" \
-d '{"title":"Dune","author":"Frank Herbert"}'
Once that works, move to a proper client for the fiddly cases — checking headers, saving request collections, testing the 422 path repeatedly. Any of the standard options will do the job.
Where REST still wins, and where it doesn't
REST isn't the only game in town anymore. GraphQL lets clients request exactly the fields they need. gRPC is faster for service-to-service chatter inside a backend. And APIs designed for AI agents to consume — ones that expose tools an agent can call rather than endpoints a human browses — are a genuinely different design problem, since the "client" no longer reads your documentation.
None of that makes REST obsolete. It's still the default for public-facing HTTP services because it's cacheable, debuggable with a browser, and understood by every developer you'll ever hire. If you're building your first API, REST is the right call, and it will remain the right call for most things you build over the next several years.
The thing that separates a working API from a good one was never the framework or the verb choices. It's whether the person on the other end can trust what your response means. Every 404 you return honestly, every 422 that explains which field failed, every 201 that confirms something was actually created — those small decisions are the whole job. Write them down somewhere. Your future self, debugging at midnight six months from now, will be grateful you did.