Express.js REST API


Express.js REST API

Anna
Hey Michael, welcome back! Today we're diving into building REST APIs with Express.js, which is super relevant for anyone looking to develop robust web services. Even if you're new to Express, we'll guide you through it.

Michael
Absolutely, Anna. And the great thing is, you don't need to be an Express guru to follow along. But a basic understanding of what a RESTful API is will definitely help, as that's exactly what we're setting out to build.

Anna
Exactly. So, let's jump right in. The very first step for any project is to set up our environment. We need to create a directory where our Express application will live. It’s like laying the foundation for our digital house.

Michael
Right. We'll open up our terminal, navigate to where we want our project, and create a new directory. For this crash course, we're building a simple To-Do application, so we'll call our directory 'todos-app' or something similar.

Anna
And within this 'todos-app,' we'll be implementing all the standard CRUD operations: creating new to-dos, fetching all to-dos or a specific one, updating their status, and, of course, deleting them. It covers all the basics.

Michael
That's right. Once the directory is set up, we'll open it in our code editor, like VS Code. If you don't have the `code .` command set up, no worries, just open it manually. The next crucial step is to initialize our Node.js application.

Anna
Since Express is a framework built on Node.js, Node.js needs to be installed first. We initialize our Node application using `npm init -y`. This creates our `package.json` file, which is essentially the manifest for our project.

Michael
The `package.json` file is where all our project's metadata and dependencies live. The only dependency we actually need for this project is Express itself. So, we'll run `npm install express` to get that installed.

Anna
Super simple, right? It usually takes just a few seconds. Once Express is installed, you'll see it listed in your `package.json` and in the `node_modules` folder. Now, we're ready to create our Express server.

Michael
The core of our Express application will reside in a file, typically named `index.js` or `main.js`. We'll stick with `index.js`. First, we import Express using `const express = require('express');`.

Anna
Then, we create an instance of our Express application by calling `const app = express();`. This `app` object is what we'll use to define our routes, middleware, and essentially manage our server.

Michael
And the final piece for a runnable server is to tell it to listen on a specific port. We use `app.listen(3000, () => console.log('Listening on port 3000'));`. Port 3000 is a common choice for development.

Anna
So, with those few lines, we've essentially built out a basic Express application. To run it, we simply execute `node index.js` in our terminal. You'll see the 'Listening on port 3000' message.

Michael
Now, if you open your browser and navigate to `localhost:3000`, you'll probably see a 'Cannot GET /' message. This is expected because we haven't defined any routes yet for our API to respond to.

Anna
Exactly. REST APIs expose routes, each designed for specific actions or resources. For our To-Do app, we'll need routes to get all to-dos, get a single to-do, add a to-do, update one, and delete one.

Michael
Let's start with our first route: fetching all to-dos. We use `app.get()` because we're retrieving data. The `get` verb is standard for this operation, ensuring our API is truly RESTful.

Anna
The first parameter to `app.get()` is the path, which will be `/todos`. The second is a callback function that takes `req` (request) and `res` (response) as parameters. These are crucial for handling client interactions.

Michael
The `req` object contains all the information about the incoming request from the client, like data in the body or parameters. The `res` object is what we use to send back our response to the client after processing the request.

Anna
So, inside our `app.get('/todos', ...)` handler, we'll define a simple array of to-dos. For now, it'll just be in memory. We'll respond with `res.json(todos)` to send this array back as JSON data, which is standard for APIs.

Michael
After making changes to our `index.js`, we'd normally have to stop and restart the server to see them. To avoid this, we'll install `nodemon` globally using `npm install -g nodemon`. This enables hot-reloading.

Anna
With `nodemon` installed, we'll add a 'dev' script to our `package.json` that runs `nodemon index.js`. Now, `npm run dev` will automatically restart our server whenever we save changes, making development much smoother.

Michael
Now, let's test our `GET /todos` route. You can do this right in your browser by going to `localhost:3000/todos`, and you should see an empty JSON array if our `todos` array is empty. Or, even better, use Postman.

Anna
Postman or Insomnia are excellent tools for API testing. They allow us to easily send various HTTP requests and inspect the responses. We can select 'GET' as the verb and send a request to `localhost:3000/todos`.

Michael
When we send that GET request, we should see our array of to-dos, even if it's empty initially. This confirms our first route is working correctly and our server is responding as expected.

Anna
Next up, adding new to-dos. For this, we'll use the `POST` verb. So, it's `app.post('/todos', ...)` This verb is specifically used when you're sending data to the server to create a new resource.

Michael
Right. In a POST request, the data for the new to-do, like its title, will be sent in the request body. This is where the `req` object comes in handy, specifically `req.body`.

Anna
Before we can access that JSON data from `req.body`, we need to tell Express to parse it. We do this with `app.use(express.json());`. This line is a middleware, and it's essential for processing JSON request bodies.

Michael
Middleware functions run before the route handler. `express.json()` parses incoming requests with JSON payloads, making `req.body` available. We'll talk more about middleware later, but for now, just know it's crucial.

Anna
Inside our `app.post` handler, we'll extract the title from `req.body.title`. Then, we'll construct a new to-do object, giving it a unique ID, the title, and setting `completed` to `false` by default.

Michael
For unique IDs, we'll install the `uuid` package using `npm install uuid`. We can then import `v4` from `uuid` and call `v4()` to generate a unique string ID for each new to-do. This is important for identifying individual items.

Anna
After creating the new to-do, we'll push it into our `todos` array. As a best practice, we'll then respond to the client with the newly created to-do object using `res.json(newTodo)`. This confirms the creation.

Michael
Now, let's test the POST request using Postman. We'll set the verb to 'POST', the URL to `localhost:3000/todos`, and in the 'Body' tab, select 'raw' and 'JSON'. Here, we can enter `{ "title": "Pet the cat" }`.

Anna
When we send this request, we should get back the newly created to-do with its unique ID and `completed: false`. If we then make a GET request to `/todos`, we'll see our new item in the array!

Michael
Awesome. The next logical step is to be able to fetch a single to-do. Again, this is a retrieval operation, so we'll use `app.get()`. But how do we specify which to-do we want?

Anna
We'll use a dynamic parameter in the route path: `app.get('/todos/:id', ...)`. The `:id` part tells Express that this segment of the URL is a placeholder for a unique identifier. This is crucial for retrieving specific resources.

Michael
Inside the handler, we can access this dynamic `id` using `req.params.id`. We'll destructure it for cleaner code: `const { id } = req.params;`. This gives us the ID to search for.

Anna
Then, we'll use the `find` method on our `todos` array to locate the to-do whose `id` matches the one from `req.params.id`. Once found, we respond with `res.json(foundTodo)`. If not found, we might send a 404 error, but for now, we'll keep it simple.

Michael
A quick note: because our `todos` array is in memory, it resets whenever the server restarts. In a real application, you'd persist this data in a database. But for learning Express, an in-memory array is perfectly fine.

Anna
To test this, we'd first create a to-do with a POST request, copy its generated ID, and then use that ID in a GET request to `localhost:3000/todos/:id`. We should get back just that specific to-do object.

Michael
Next, let's tackle updating a to-do. Typically, for partial updates, we use the `PATCH` verb, but for this simple toggle of a boolean, `PUT` is also acceptable. We'll stick with `PUT` for now, so `app.put('/todos/:id', ...)`.

Anna
Similar to getting a single to-do, we need the `:id` parameter to identify which to-do to update. We'll extract `id` from `req.params` just like before.

Michael
Inside the handler, we'll find the index of the to-do with the matching ID using `todos.findIndex()`. This gives us its position in the array. Then, we can directly update its `completed` status by toggling it: `!todos[index].completed`.

Anna
We'll respond with `res.json(todos[index])`, returning the updated to-do object. This way, the client knows the change was successful and what the new status is.

Michael
To test, create a to-do, then make a PUT request to `localhost:3000/todos/:id` with its ID. You'll see the `completed` status toggle between `true` and `false` with each request.

Anna
Finally, we need to implement deletion. As you might guess, we'll use the `DELETE` verb. So, it's `app.delete('/todos/:id', ...)`.

Michael
Again, we need the `:id` from `req.params` to identify the to-do to be removed. Instead of modifying the array directly, we'll use `todos.filter()` to create a new array that excludes the to-do with the matching ID.

Anna
We'll reassign our `todos` variable to this new filtered array, effectively removing the item. We then respond with `res.json(todos)` to show the client the updated list without the deleted item.

Michael
Testing this involves creating a to-do, then making a DELETE request to `localhost:3000/todos/:id` with its ID. A subsequent GET request to `/todos` should confirm the item is gone.

Anna
Now, our `index.js` file is getting a bit long with all these routes. A common best practice for larger applications is to organize routes into separate files. This improves readability and maintainability.

Michael
Exactly. We'll create a `routes` directory, and inside it, a `todos.js` file. All our to-do specific routes will move into this new file.

Anna
In `todos.js`, instead of `app.get`, `app.post`, etc., we'll use `const router = express.Router();` and then `router.get`, `router.post`, and so on. This `router` object works similarly to `app` but for modular routing.

Michael
Crucially, at the end of `todos.js`, we need to `module.exports = router;` to make these routes available to our main application. Don't forget to move the `uuid` import and the `todos` array there too.

Anna
Back in `index.js`, we'll replace all the individual `app.get`, `app.post` calls with a single line: `app.use('/todos', require('./routes/todos'));`. This tells Express to use the routes defined in `todos.js` for any request starting with `/todos`.

Michael
This `'/todos'` path in `app.use()` is a base path. It means that within `todos.js`, we can remove `/todos` from our individual route definitions. For example, `router.get('/')` will now correspond to `GET /todos`.

Anna
This significantly cleans up our `index.js` file and keeps our routes organized. It's a fundamental pattern for building scalable Express applications. All our previous API calls should still work exactly as before.

Michael
Finally, let's talk more about middleware. We briefly touched on `app.use(express.json())`. Middleware functions sit between the incoming request and the final route handler. They can perform operations, modify the request/response, or even end the request-response cycle.

Anna
A common use case for middleware is authentication. Imagine we want to check if a user is logged in before allowing them to access certain routes. We can create a middleware function for that.

Michael
Let's create a `middleware` directory and a `checkAuth.js` file. Inside, we'll export a function that takes `req`, `res`, and `next` as parameters. `next` is a special function that, when called, passes control to the next middleware or the route handler.

Anna
For a simple authentication check, we'll look for a custom header called `authenticated`. If `req.header('authenticated')` is 'yes', we'll call `next()` to proceed. Otherwise, we'll send a `403 Forbidden` response with an 'Not authenticated' message.

Michael
To integrate this, we simply add `checkAuth` as a second parameter to our route definitions, before the `(req, res)` callback. For example, `router.get('/', checkAuth, (req, res) => { ... });`.

Anna
Now, if we send a request without the `authenticated: yes` header, or with `authenticated: no`, we'll get our 403 error. If the header is set to 'yes', the request will proceed to the route handler as usual.

Michael
This is a simple illustration, but it shows the power of middleware. You can stack multiple middleware functions, and they execute in order, making your API robust and secure.

Anna
And that pretty much covers the essentials of building a REST API with Express.js! We've learned how to set up a server, define routes, handle different HTTP verbs, use parameters, process request bodies, organize our code, and implement basic middleware.

Ask anything
We've read this whole study set, so questions about it get the best answers.