Node.js Express API


Node.js Express API

Maria
Hey Anna! Today we're diving into building a RESTful web API service using Node.js and Express. It's going to be a backend-focused session, but we'll eventually create a frontend with Angular.

Anna
That sounds great, Maria! So we're essentially building the data layer that a frontend application would interact with, right? And we'll be able to perform all the standard CRUD operations: Create, Read, Update, and Delete.

Maria
Exactly! Our bookstore application will need to handle requests for book data and genres. This means we'll implement GET requests to retrieve data, POST requests to add new entries, PUT requests to update existing data, and DELETE requests to remove records.

Anna
I like that we're starting from scratch. No generators or scaffolding! While those are convenient for quick setups, building it manually really helps understand what's happening under the hood, especially when you're learning.

Maria
Definitely. It's all about understanding the fundamentals. So, let's talk about the core technologies we're using. First up is Node.js, which allows us to run JavaScript on the server side. It's very powerful, leveraging the same JavaScript engine as Google Chrome.

Anna
Node.js is fantastic for backend development. And installing it is usually straightforward, either via an installer on Windows or package managers on Linux. What about the web framework we'll be using?

Maria
For our web framework, we're using Express. It's a minimalist, flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It's incredibly powerful for handling requests and even using template engines.

Anna
Express makes building APIs much easier. And since it's an npm module, we'll install it using npm, which comes bundled with Node.js. What are we using for our data storage, Maria?

Maria
For our data store, we're going with MongoDB. It's a popular NoSQL database, also easy to install. I've even got a video walking through the Windows installation if anyone runs into trouble. It's perfect for our book and genre data.

Anna
MongoDB is a great choice for its flexibility. And when we eventually build the frontend, we'll be using AngularJS, a very powerful client-side framework built on JavaScript. It's definitely worth learning if you haven't already.

Maria
Absolutely, Angular is highly popular and robust. To interact with MongoDB from our Node.js application, we'll be using Mongoose, an object data modeling (ODM) library for MongoDB and Node.js. It simplifies database interactions significantly.

Anna
Mongoose makes working with MongoDB feel much more natural within Node.js. And for our command line, we can use the standard Windows command line or PowerShell, but you're going with Git Bash, right?

Maria
Yes, Git Bash provides a more Linux-like terminal experience on Windows, which I find very helpful. With all our tools in place, let's start by creating our project folder, which we'll call 'bookstore'.

Anna
Alright, 'bookstore' it is. So, we'll need a main `app.js` file as the entry point, and since we're using Mongoose, a 'models' folder for defining our data schemas, correct?

Maria
That's right. And a crucial file for any Node.js project is `package.json`. We can create it using `npm init` from our terminal, which will prompt us for some project details like name, version, and description.

Anna
Yes, `package.json` is essential for managing dependencies. After creating it, we'll manually add our dependencies like Express, Body Parser, and Mongoose, specifying that we want the latest versions with an asterisk.

Maria
Exactly. Body Parser is key because it'll help us process data from forms, especially for POST requests. Once we've listed them, a simple `npm install` command will fetch and install all those modules locally for our project.

Anna
Got it. So after installation, we'll open `app.js` and start by requiring our necessary modules: Express, Body Parser, and Mongoose. Then we'll instantiate our Express application.

Maria
Precisely. And immediately after that, we'll establish our connection to MongoDB using `mongoose.connect()`, specifying our database name, which will be 'bookstore'. Mongoose will handle creating it if it doesn't exist.

Anna
Connecting to the database early on makes sense. Then we can define our first route. We'll start with a basic GET request for the homepage, represented by a slash '/', to ensure our server is up and running.

Maria
Yes, `app.get('/')` will handle that. Inside the callback function, we'll use `res.send('Hello World')` to send a simple message to the browser. Crucially, we also need `app.listen(3000)` to tell our app to run on port 3000.

Anna
And a `console.log` message like 'Running on Port 3000' is always good for confirmation. So, after setting that up, we can run `node app.js` and visit `localhost:3000` to see our 'Hello World' message?

Maria
That's the initial check! Now, for an actual API, we want users to interact through a `/api` endpoint. So, for the root path, we'll change the message to guide them to `/api/books` or `/api/genres`.

Anna
That's a good user experience for an API. And to avoid restarting the server manually every time we make a code change, we can install and use `nodemon` globally with `npm install -g nodemon`. Then we just run `nodemon app.js`.

Maria
Nodemon is a lifesaver for development! Now, before we build out the API routes, let's set up our MongoDB database. We'll open the Mongo Shell and create our 'bookstore' database and then our 'books' and 'genres' collections.

Anna
So, `use bookstore`, then `db.createCollection('books')` and `db.createCollection('genres')`. After that, we can insert some sample data directly into the collections using `db.genres.insert()` and `db.books.insert()` to populate them.

Maria
Precisely. We'll add a few genres like 'Suspense' and 'Self-Help', and then some book entries with titles, genres, descriptions, authors, publishers, page counts, image URLs, and buy URLs. This gives us data to work with.

Anna
Inserting sample data manually like this in the shell is great for initial setup and testing. And `db.collection.find().pretty()` helps to view the data in a readable format. Now, back to our `app.js` file.

Maria
Yes, we'll create our first actual API route. We want `app.get('/api/genres')` to return all the genres in JSON format. But before that, we need to define our Mongoose models.

Anna
Right, the models folder! So, in `models/genre.js`, we'll define a Mongoose schema for 'Genre' with a 'name' field of type String, marked as required, and a 'create_date' field with a default value of `Date.now`.

Maria
Exactly. And we'll export this model using `module.exports = mongoose.model('Genre', genreSchema)` so we can access it from other files. Inside the model, we'll also define a static method, `getGenres`, to fetch all genre documents.

Anna
Having the database interaction logic within the model itself is good practice. The `getGenres` function will use `Genre.find()` and accept a callback and an optional limit. Now, back in `app.js` to implement the route.

Maria
In `app.js`, we'll require our `genre` model. Then, in our `/api/genres` GET route, we'll call `Genre.getGenres()`, passing in a callback. If there's an error, we throw it; otherwise, we respond with `res.json(genres)`.

Anna
Perfect! This should now return our genres as JSON. Next, we'll do the same for books. We'll create `models/book.js`, define its schema with fields like title, genre, description, author, publisher, pages, image_url, and buy_url.

Maria
Yes, and just like genres, we'll add a `getBooks` static method to the book model to retrieve all books. Then in `app.js`, we'll set up `app.get('/api/books')` to call this function and respond with the book data.

Anna
Great! So, we can fetch all genres and all books. What about fetching a single book by its ID? That's a common API pattern.

Maria
Absolutely. For that, we'll create a new route: `app.get('/api/books/:_id')`. The `:_id` part is a placeholder for the book's ID that will be passed in the URL. In the book model, we'll add `getBookById`.

Anna
The `getBookById` function will take the ID as an argument and use `Book.findById()` from Mongoose to retrieve the specific book. Then, back in `app.js`, we'll extract the ID from `req.params._id` and pass it to our model function.

Maria
That's the correct flow. Now we can retrieve individual books. The next step is adding data. Let's start with genres again. In the genre model, we'll create an `addGenre` function that uses `Genre.create()` to save a new genre object.

Anna
And in `app.js`, for `app.post('/api/genres')`, we'll need to get the genre data from `req.body`. This is where Body Parser becomes crucial. It parses the incoming request body, making it accessible as `req.body`.

Maria
Crucially, we need to initialize Body Parser middleware in `app.js` by adding `app.use(bodyParser.json())` at the top. This ensures that incoming JSON request bodies are parsed correctly.

Anna
Ah, the middleware! That's why post requests might have been hanging. After setting that up, we can use a tool like Postman or the Rest Easy Chrome app to send a POST request to `/api/genres` with a JSON body containing the new genre name.

Maria
Exactly. With the 'Content-Type: application/json' header and a JSON body like `{"name": "Romance"}`, we can test adding a new genre. After verifying it in the Mongo shell, we'll do the same for books.

Anna
So, in the book model, we'll create an `addBook` function using `Book.create()`. And then, in `app.js`, we'll set up `app.post('/api/books')` to receive the book data from `req.body` and call `Book.addBook()`.

Maria
That completes our POST functionality for both genres and books. It's important to note for production apps, you'd add authentication and validate the incoming data more rigorously, but for now, this shows the core functionality.

Anna
Understood, security and validation are vital in real-world applications. Now, let's move on to updating data. We'll start with genres again.

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