DEV Community

Margaret W.N
Margaret W.N

Posted on

Habit Tracker API: Project Setup

Onto incomplete project number...mmh... seems like i lost count. Today i'll setup the skeleton of an Api project i intend to work on that adds, retrieves and deletes habits. I'll be using Node.js and Express. Let's get started.

Run npm init in the project folder, accept all defaults. That creates a package.json file

Install express npm install express

Create an app.js file and include express

const express = require('express');
Enter fullscreen mode Exit fullscreen mode

Create an instance of express

const app = express();
Enter fullscreen mode Exit fullscreen mode

Set up the port

const port = 4000;
Enter fullscreen mode Exit fullscreen mode

Create a router

const router = express.Router():
Enter fullscreen mode Exit fullscreen mode

Handle some routes and chain a get/post function.

router.route('/habits')
  .get((req, res) => {
    //Some random code to test with
    const response = 'My api';
    return res.json(response);
  })
  .post();
Enter fullscreen mode Exit fullscreen mode

Use our router

app.use('/habittracker', router);
Enter fullscreen mode Exit fullscreen mode

Set up the server to listen for requests

app.listen(port, () => {
  console.log(`listening on Port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Installl nodemon : npm install nodemon. Nodemon watches our files for changes and restarts our server. Update the scripts in the package.json with:

"start": " nodemon node app.js",
Enter fullscreen mode Exit fullscreen mode

This allows us to use npm start to start the server.

Let's start the server, head over to postman and send a get request
Alt Text

It's working!

There we have it, over to procrastination.

Another day down: Day 8!

Top comments (0)