Using Node.js to create a REST API around a SQL database

A few code snippets for how you can quickly stand up a SQL database, and provide a REST API for DB read/writes

I was helping out a team at a hackday hosted at Hursley last week. One of the things they wanted for their hack was a SQL database to put sensor data in, which they could access via a REST API. And they wanted it in node.js.

I’d never used Node before, so I used this as a chance to give myself a first crash-course.

I’m not saying this is the way to do this in Node, as it’s the result of my first hour’s tinkering. But it worked, and I mostly wanted to share how quick and easy it was.

Each time you run it, it inserts a row, and then selects and prints all of the rows in the table.

So each time you run it, you get one more row than the time before. After a few times…

$ node nodejs_simple_file_db.js
This app was run at 1401967100001
This app was run at 1401967101397
This app was run at 1401967103406
This app was run at 1401967115812
This app was run at 1401967116905
This app was run at 1401967117834
This app was run at 1401967118381
This app was run at 1401967118676
This app was run at 1401967118970
This app was run at 1401967119212

server$ node nodejs_db_with_restapi.js
Submit GET or POST to http://localhost:3000/data

client$ curl -X GET http://localhost:3000/data
{"count":5}

$ curl -X POST http://localhost:3000/data

$ curl -X GET http://localhost:3000/data
{"count":6}

And that’s it.

This whole thing took me no time at all – probably about 40 minutes. Despite having never touched Node.js before, I’d managed to pull together a basis for the hack from a few samples. For the last few years, most of the code I’ve written each day has been in Java, so this made a fun change.