Posts match “ api ” tag:

授權方式(Auhorization): CC-BY 4.0

Introduction

突然發覺自己事情其實很要求,雖然沒有說完美,但至少要按照一些標準,總之就是要打造自己的rest api停止去直接連資料庫。
這邊我們使用nodejs + expressjs + mysql來完成要求

Data Format

*id, room, time, value1, value2, ..., value8

First URL Routing

既然是rest api就要考慮好url routing
從Data Format可以規劃出以下的url route
http://api.example.com/room/start_datetime/end_datetime/value*
實際上調用情況也要先想好
e.g.:

  1. http://api.example.com/room1/2013-05-07%2011:00/2013-05-08%2012:00/value1
  2. http://api.example.com/room2/2013-05-07%2011:00/2013-05-08%2012:00/all

JSON format Callback

事先規劃好回傳的JSON Foramt
{
time: 2013-05-07 11:00:00
value1: 231
}

Implement

api.js

var mysql = require('mysql')

var client = mysql.createConnection({...});

exports.findRecord = function (req, res) {
    var room = req.params.room,
        startDate = req.params.startDate,
        endDate = req.params.endDate,
        data = req.params.data;
  // 處理 params
    sql = "select ....";

  client.query(sql, function (err, rows, fields) {
    res.jsonp(rows);
  });
};

app.js

把api.js包進來

api = require('./routes/api');

設定route path

app.get('/:room/:startDate/:endDate/:data', api.findRecord);

基本上這樣就完成了 REST API!
非常的簡單 :)

ps 記得要在package.json裡面設好"dependencies