A Yeoman generator for building a REST API in minutes using Express + MongoDB.
The main generator will scaffold a project that is identical to the express command line generator as of express 3.4.2.
The rest-rest generator adds the following: 1 A resource generator for generating the routes and queries required to offer basic CRUD operations on the resource. 2 Scaffolding for a connection to a MongoDB instance using the Mongoose driver. 3 A basic logger using winston
The resource generator will generate the routes and queries required to offer basic CRUD operations on the resource.
All CRUD APIs follow the convention:
Action | HTTP Verb | path |
---|---|---|
Create | POST | /resource |
Read | GET | /resource/:id |
Update | PUT | /resource/:id |
Delete | DELETE | /resource/:id |
Get the full list | GET | /resource |
If you wish to customize the code that has been generated, here's where to look:
- The routes are defined in ./routes/index.js
- The Schema is defined in lib/db.js
- The quries are defined in resource/.js
Mongoose is currently being used as the MongoDB driver. The file lib/db.js contains the connection and schema definition.
A basic logger is created, the details are in the file lib/log.js. By default it creates a log file named logs/development.log. If the environment variable NODE_ENV is set to 'production' then the file will be named logs/production.log.
- Make sure you have yo installed on the latest version.
$ npm install -g yo
- Ensure that MongoDB is installed and running.
-
Install the generator
$ npm install -g generator-rest-express
-
Create a project directory and run the generator
$ mkdir myApp $ yo rest-express
-
Reply to the prompts asking you for your MongoDB connection details
$ [?] IP address where MongoDB is running? (127.0.0.1) $ [?] Database name? (myApp)
-
Generate your first resource API
$ yo rest-express:resource user
-
Start your node server
$ node app.js
-
Create a few resources using curl
$ curl -d "firstname=Brian" http://localhost:3000/users $ curl -d "firstname=Jerry" http://localhost:3000/users
-
Retreive the list resources using curl
$ curl http://localhost:3000/users