COVID19 Lockdown Dev Log – Day 33, Creating REST API Endpoints In Express.js

What I Worked On

A Taskmanager app.

What I Learned

Creating API endpoints in Express.js

I have a MongoDB database running on my machine. The database contains a collection of users and is used with the Taskmanager app I’m building. To access the list of users we can create an API endpoint in Express.js. Let’s create a “Read” endpoint:

// index.js

const express = require('express');
require('./db/mongoose');
const User = require('./models/user');

const app = express();

// Set Express to automatically parse JSON so we can access it in request handlers
app.use(express.json())

// Read users
app.get('/users', (req, res) => {

})

So, here in index.js we’re importing the express module, the database connection, and the User model. The database connection is made with Mongoose:

// mongoose.js

const mongoose = require('mongoose');

// create connection string AND database name after portnumber
const connectionUrl = 'mongodb://127.0.0.1:27017/task-manager-api'

mongoose.connect(connectionUrl, {
    useNewUrlParser: true,
    useUnifiedTopology: true
})

And the User model is structured like this (I’ve left out some of the settings to make sure the file didn’t become too long here 😀 ):

// user.js

const mongoose = require('mongoose');
const validator = require('validator');

const User = mongoose.model('User', {
    name: {
        type: String,
        ...// more key-value pairs
    },
    email: {
        type: String,
        ...// more key-value pairs
    },
    password: {
        type: String,
        ...// more key-value pairs
    },
    age: {
        type: Number,
        ...// more key-value pairs
    }
})

module.exports = User;

Back to the index.js file. We have the call setup and all we need to do is the tell Express.js what to do when we request the “/users” URL (localhost:3000/users). We do this with the get() function. It takes two arguments: the URL and a callback function, which gives access to the request (req) and the response(res):

// index.js

//...module imports

app.get('/users', (req, res) => {
    User.find({}).then((users) => {
        res.send(users)
    }).catch((error) =>{
        res.status(500).send()
    })
})

We use the Mongoose method find() and pass in an empty object, which fetches all of the users, and returns a Promise. Using then() we access the Promise data users when the Promise resolves. Using the Express method send() we provide the array of users as the response (res). Should the Promise not resolve, we return an error message in the catch() block.

That’s cool and all, but let’s try and make an actual request with Postman and see the endpoint in action 😀 With Postman I create a GET request to the URL: “localhost:3000/users” and receive the list of users:

Great success! 😀 And yes, the password is returned as a String at the moment. This will ofc. be hashed later on 😀

It is also possible to request info about a single user, by typing in the user’s _id in the URL: “localhost:3000/users/_id”. This is possible by making a similar Read endpoint like the previous one:

// index.js

app.get('/users/:id', (req, res) => {
    //use Express' 'req.params' to access the dynamic '/:id' value
    const _id = req.params.id

    User.findById(_id).then((user) => {
        if (!user) {
            return res.status(404).send()
        }
        
        res.send(user)
    }).catch((error) => {
        res.status(500).send()
    })
})

Let’s test it in Postman by entering the id of the first user we got back from the list of users. The URL “localhost:3000/users/5eb56c07e457731426d73252” returns the following response in Postman:

Alright. Let’s end the post here. It’s beginning to get rather long 😀 Now you hopefully have an idea of how to create API endpoints with Express.js 😀

What Distracted Me During The Day

  • Youtube. Got sucked into a void of watching content from Traversy Media – whoops 😀

Resources