Mongoose Express REST-full API
merest provides easy way to expose Mongoose models as REST-full api. It creates pointed bellow end-points:
For each api-application:
all api options
: OPTIONS ..\
For each exposed model
model api options
: OPTIONS ..\model-plural-name\search
: GET ..\model-plural-name\create
: POST ..\model-plural-name\details
: GET ..\model-plural-name\:idupdate
: POST ..\model-plural-name\:iddelete
: DELETE ..\model-plural-name\:id
Generally merest allows to:
- create rest api for many models
- create many rest interfaces for one model
- restrict the set of documents that are accessible via API
- configure of each mentioned above end-points
- expose static and instance methods of the Model
- create and expose swagger documentation of your rest api
- serve the swagger-ui (merest-swagger required)
Documentation
http://dscheglov.github.io/merest/
Installation
npm i --save merest
merest doesn't install Mongoose or Express in production environment. It is crucial to embed API into your project correctly. You should to install these components by yourself.
Recommended components:
npm i --save mongoose express body-parser method-override
To provide swagger documentation and user interface additionally the merest-swagger should be installed:
npm i --save merest-swagger
Getting started with merest
'use strict'; const merest = ;const express = ;const bodyParser = ;const methodOverride = ; // Defining modelconst mongoose = ;const Contact = mongoose;mongoose; // Creating the Express application to serve APIconst api = ; api; // Parsing JSON-bodiesapi; // Supporting HTTP OPTIONS and HTTP DELETE methods api; // Exposing our API api;
Calling API:
curl -X OPTIONS http://localhost:8000/
Output:
[ ["options","/","List all end-points of current application"], ["options","/contacts/","List API-options for contacts"], ["get","/contacts/","List/Search all contacts"], ["post","/contacts/","Create a new Contact"], ["get","/contacts/:id","Find a Contact by Id"], ["post","/contacts/:id","Find a Contact by Id and update it (particulary)"], ["delete","/contacts/:id","Find a Contact by Id and delete it."]]
Getting contact list:
curl -X GET http://localhost:8000/contacts
Output:
[ , ]
Integrating merest into existing projects
'use strict'; const merest = ; // to support SwaggerUIconst express = ;const bodyParser = ;const methodOverride = ; // Defining modelconst mongoose = ;const Contact = mongoose;mongoose; const app = ;// Creating the Express application to serve APIconst api = title: 'Contact List API' host: 'localhost:8000' // Assign correct host that could be accessed from your network path: '/api/v1' options: false // we do not need the OPTIONS any more; app; // Parsing JSON-bodiesapp; // Supporting HTTP OPTIONS and HTTP DELETE methods api; // Exposing our APIapi; // Exposing swagger-ui app; // mounting API as usual sub-application app;
Going to swagger-ui in browser: http://localhost:8000/swagger-ui