Build Node.js RESTful APIs in 10 Minutes

 

https://www.codementor.io/@olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd#what-is-rest

 

What is REST?

REST is an acronym for Representational State Transfer. It is web standards architecture and HTTP Protocol. The REST architectural style describes six constraints that were originally communicated by Roy Fielding in his doctoral dissertation and defines the basis of RESTful-style as:

  1. Uniform Interface
  2. Stateless
  3. Cacheable
  4. Client-Server
  5. Layered System
  6. Code on Demand (optional)

RESTful applications use HTTP requests to perform four operations termed as CRUD (C: create, R: read, U: update, and D: delete). Create and/or update is used to post data, get for reading/listing data, and delete to remove data.

RESTful is composed of methods such as; base URL, URL, media types, etc.

In this tutorial, we will learn how to create a RESTful API using Node.js.

Tools:

Getting started

For the purpose of this tutorial, I’ll work you through creating a RESTful API. To achieve this, we will create a RESTful todo list API (i.e. endpoints that will create a task, get or read list of all tasks, read a particular task, delete a task, and update a task).

Assumptions

I presume that you already have your environment set up (i.e Node.js and MongoDB is installed).

Kindly run npm -v and mongo --version as these will show you the version of NPM and MongoDB installed on your machine.

If you don’t have it installed, kindly go through this link on how to install it in order for us to create a server in Node and Mongodb.

If you do have Node and MongoDB installed, let's begin the tutorial with the following basic steps.

Open your terminal and kindly follow the following steps

    1. Create a Folder name todoListApi - mkdir todoListApi

    2. Navigate to the root of your newly created folder - cd todoListApi

    3. Create a package.json file - npm init
      Package.json is a file that gives the necessary information to npm which allows it to identify the project as well as handle the project's dependencies.
      npm init will prompt you to enter some information such as the app name, description, version, author, keyword and also ask if what you see is what you like.
      You should have something like this eventually.

       

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      {
        "name": "todolistapi",
        "version": "1.0.0",
        "description": "",
        "main": "index.js",
        "scripts": {
          "start": "nodemon server.js",
          "test": "echo \"Error: no test specified\" && exit 1"
        },
        "author": "",
        "license": "ISC",
        "dependencies": {
          "body-parser": "^1.19.0",
          "express": "^4.17.1",
          "mysql": "^2.17.1",
          "nodemon": "^2.0.2"
        }
      }

          

    4. Create a file called server.js - touch server.js.
      In this server, we will writing the protocols to create our server.

    5. Create a folder called api - mkdir api
      Inside this folder called api, create three separate folders called models, routes, and controllers by running mkdir api/controllers api/models api/routes

    6. Create todoListController.js in the api/controller folder, todoListRoutes.js in the routes folder, and todoListModel in the model folder - touch api/controllers/todoListController.js api/models/todoListModel.js api/routes/todoListRoutes.js

  

Server setup

Let's install express and nodmon, express will be used to create the server while nodmon will help us to keep track of changes to our application by watching changed files and automatically restart the server.

npm install --save-dev nodemon

npm install express --save

On successful installation, your package.json file will be modified to have the two newly installed packages.

  1. Open the package.json file and add this task to the script

"start": "nodemon server.js"

 

https://gitee.com/youhui_xm/todoListApi

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const mysql = require('mysql');
const conf = require("../../conf/db")
const pool = mysql.createPool(conf.mysql);
const common = require("../../common");
 
module.exports = {
    list_all_tasks: function (req, res) {
        pool.getConnection(function (err, connection) {
            if (err) {
                logger.error(err);
            }
            connection.query("select * from task", function (e, result) {
                if (e) {
                    logger.error(e);
                }
                if (result.length > 0) {
                    common.jsonWrite(res, result);
                }
                connection.release();
            })
        })
    },
 
    read_a_task: function (req, res) {
        pool.getConnection(function (err, connection) {
            if (err) {
                logger.error(err);
            }
            connection.query("select * from task where id = (?)", req.params.id, function (e, result) {
                if (e) {
                    logger.error(e);
                }
                if (result.length > 0) {
                    common.jsonWrite(res, result[0]);
                }
                connection.release();
            })
        })
    }
}

 

1
2
3
4
5
6
7
8
9
const todoList = require('../controllers/todoListController');
 
module.exports = function(app) {
    app.route('/tasks')
    .get(todoList.list_all_tasks);
 
    app.route('/tasks/:id')
    .get(todoList.read_a_task)
};

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
module.exports = {
    jsonWrite: function (res, ret) {
        if (typeof ret === 'undefined') {
            res.json({
                code: '1',
                msg: '操作失败',
                data: null
            });
        } else {
            res.json({
                code: '0',
                msg: '成功',
                data: ret
            });
        }
    }
}
1
2
3
4
5
6
7
8
9
module.exports = {
    mysql: {
        host: 'xxxxxxx',
        user: 'xx',
        password: 'xxxx',
        database: 'xxxx',
        port: 3306
    }
};

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const express = require('express');
const process = require('process');
const bodyParser = require('body-parser');
 
app = express();
 
port = process.env.PORT || 3000;
 
app.listen(port);
 
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
 
var routes = require('./api/routes/todoListRoutes'); //importing route
routes(app);
 
app.use(function(req, res) {
    res.status(404).send({url: req.originalUrl + ' not found'})
  });
 
console.log('todo list RESTful API server started on: ' + port);

  

 

 

2、使用 jwt web token 给相关api接口授权

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const express = require('express');
const process = require('process');
const bodyParser = require('body-parser');
const expressJwt = require('express-jwt')
const CONSTANT = require('./common/constant')
 
app = express();
 
port = process.env.PORT || 3000;
 
app.listen(port);
 
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
 
app.use(expressJwt({
  secret: CONSTANT.SECRET_KEY
}).unless({
  path: ['/login', '/signup'
}))
 
app.use(function (err, req, res, next) {
  //console.error(err);
  if (err.status === 401) {  
    res.status(401).send('invalid token')
  }
})
 
var routes = require('./api/routes/todoListRoutes'); 
routes(app);
 
routes = require('./api/routes/loginRoutes'); 
routes(app);
 
app.use(function (req, res) {
  res.status(404).send({ url: req.originalUrl + ' not found' })
});
 
console.log('todo list RESTful API server started on: ' + port);

  

1
2
3
4
5
6
7
const loginController = require('../controllers/loginController');
 
module.exports = function (app) {
    app.route('/login').post(loginController.login)
 
 
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const common = require("../../common");
const jwt = require('jsonwebtoken');
const CONSTANT = require('../../common/constant');
 
module.exports = {
    login: function (req, res) {
        if (req.body && req.body.userID) {
            console.log(req.body.userID);
        }
        if (req.body && req.body.password) {
            console.log(req.body.password);
        }
        //console.log(req);
        const token = 'Bearer ' + jwt.sign({ id: 10005 }, CONSTANT.SECRET_KEY, { expiresIn: 3600 * 24 * 15 })
        common.jsonWrite(res, token)
    }
};

 

1
2
3
4
5
const CONSTANT = {
    SECRET_KEY: 'z0bs6e44c052nj839q1l'
};
 
module.exports = CONSTANT;

  

 

  

 

 

posted on   youhui  阅读(161)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示