Está en la página 1de 20

Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.

es/blog/como-crear-una-api-rest-usando-node-js/

45 10

1 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

$ mkdir node-api-rest-example

2 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

$ brew update
$ brew install node

package.json

package.json

{
"name": "node-api-rest-example",
"version": "2.0.0",
"dependencies": {
"mongoose": "~3.6.11",
"express": "^4.7.1",
"method-override": "^2.1.2",
"body-parser": "^1.5.1"
}
}

3 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

app.js

var express = require("express"),


app = express(),
bodyParser = require("body-parser"),
methodOverride = require("method-override");
mongoose = require('mongoose');

app.use(bodyParser.urlencoded({ extended: false }));


app.use(bodyParser.json());
app.use(methodOverride());

var router = express.Router();

router.get('/', function(req, res) {


res.send("Hello World!");
});

app.use(router);

app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});

4 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

http

bodyParser methodOverride()

app.route(nombre_de_la_ruta)
.get() .post() …
express.Router()
GET Hello World

$ node app.js
Node server running on http://localhost:3000

5 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

$ git add .
$ git commit -m 'Initial commit'

models/tvshow.js

var mongoose = require('mongoose'),


Schema = mongoose.Schema;

var tvshowSchema = new Schema({


title: { type: String },
year: { type: Number },
country: { type: String },
poster: { type: String },
seasons: { type: Number },
genre: { type: String, enum:

6 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

summary: { type: String }


});

module.exports = mongoose.model('TVShow', tvshowSchema);

app.j

var mongoose = require('mongoose');


mongoose.connect('mongodb://localhost/tvshows');

var express = require("express"),


app = express(),
http = require("http"),
server = http.createServer(app),
mongoose = require('mongoose');

app.use(bodyParser.urlencoded({ extended: false }));


app.use(bodyParser.json());
app.use(methodOverride());

var router = express.Router();

router.get('/', function(req, res) {


res.send("Hello World!");
});

app.use(router);

mongoose.connect('mongodb://localhost/tvshows', function(err, res) {


if(err) {

7 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
});

$ brew update
$ brew install mongodb

$ mongod
all output going to: /usr/local/var/log/mongodb/mongo.log

node app.js

$ node app.js
Node server running on http://localhost:3000
Connected to Database

8 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

$ mongo
MongoDB shell version: 2.4.1
connecting to: test
> use tvshows
switched to db tvshows
> show dbs
local 0.078125GB
tvshows (empty)
>_

controllers/tvshows.js exports

//File: controllers/tvshows.js
var mongoose = require('mongoose');
var TVShow = mongoose.model('TVShow');

//GET - Return all tvshows in the DB


exports.findAllTVShows = function(req, res) {
TVShow.find(function(err, tvshows) {

9 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

console.log('GET /tvshows')
res.status(200).jsonp(tvshows);
});
};

findAllTVShows
tvshows

//GET - Return a TVShow with specified ID


exports.findById = function(req, res) {
TVShow.findById(req.params.id, function(err, tvshow) {
if(err) return res.send(500. err.message);

console.log('GET /tvshow/' + req.params.id);


res.status(200).jsonp(tvshow);
});
};

find() findById()

//POST - Insert a new TVShow in the DB


exports.addTVShow = function(req, res) {
console.log('POST');
console.log(req.body);

10 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

year: req.body.year,
country: req.body.country,
poster: req.body.poster,
seasons: req.body.seasons,
genre: req.body.genre,
summary: req.body.summary
});

tvshow.save(function(err, tvshow) {
if(err) return res.status(500).send( err.message);
res.status(200).jsonp(tvshow);
});
};

tvshow

.save()

//PUT - Update a register already exists


exports.updateTVShow = function(req, res) {
TVShow.findById(req.params.id, function(err, tvshow) {
tvshow.title = req.body.petId;
tvshow.year = req.body.year;
tvshow.country = req.body.country;
tvshow.poster = req.body.poster;
tvshow.seasons = req.body.seasons;
tvshow.genre = req.body.genre;
tvshow.summary = req.body.summary;

11 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

if(err) return res.status(500).send(err.message);


res.status(200).jsonp(tvshow);
});
});
};

//DELETE - Delete a TVShow with specified ID


exports.deleteTVShow = function(req, res) {
TVShow.findById(req.params.id, function(err, tvshow) {
tvshow.remove(function(err) {
if(err) return res.status(500).send(err.message);
res.status(200).send();
})
});
};

.findById()
.remove()
.save()

app.js

var TVShowCtrl = require('./controllers/tvshows');

// API routes

12 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

tvshows.route('/tvshows')
.get(TVShowCtrl.findAllTVShows)
.post(TVShowCtrl.addTVShow);

tvshows.route('/tvshows/:id')
.get(TVShowCtrl.findById)
.put(TVShowCtrl.updateTVShow)
.delete(TVShowCtrl.deleteTVShow);

app.use('/api', tvshows);

13 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

{
"title": "LOST",
"year": 2004,
"country": "USA",
"poster": "http://ia.media-imdb.com/images/M/MV5BMjA3NzMyMzU1MV5BMl5BanBnXkFtZTc
"seasons": 6,
"genre": "Sci-Fi",
"summary": "The survivors of a plane crash are forced to live with each other on
}

SEND

14 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

mongod

$ mongo
MongoDB shell version: 2.4.1
connecting to: test
> show databases
tvshows 0.203125GB
> use tvshows
switched to db tvshows
> show collections
system.indexes
tvshows
> db.tvshows.find()
{ "title" : "LOST", "year" : 2004, "country" : "USA", "poster" : "http://ia.media-

http://localhost:3000/tvshows

15 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

GET
tvshows/:id

PUT DELETE POST

16 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

45 10

17 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

18 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

41 Comentarios 1

alx_lopz •

Hola carlos quisiera saber como habilito CORS ya que mi navegador me lanza este error
en consola: "XMLHttpRequest cannot load http://api.midominio/colores. No 'Access-
Control-Allow-Origin' header is present on the requested resource. Origin
'http://localhost:9000' is therefore not allowed access". Subí mi api a un server con nginx,
si entro a api.midominio/colores si me despliega el json en crudo, pero cuando lo conecto
en mi app angular no carga los valores y me lanza dicho error.
• •

Carlos Azaustre Moderador •

Hola @alx_lopz
Eso puedes arreglarlo con este paquete: https://www.npmjs.com/package/... e
indicando la URL donde tienes tu app angular :)

Saludos!
• •

Luca Enzô •

Grandísimo ejemplo. Muy práctico y dinámico además de contar con el repositorio


completo.
Una de las mejores extensiones para probar la app la ppodréis encontrar en
http://insomnia.rest/. Es mas cómoda e intuitiva que restconsole.com, cuya web además
ya no existe.
• •

Frank •

Yo cuando trato de hacer un tutorial tuyo no me sale nunca, no sé que clase de brujeria
es esta pero igual gracias por los tutoriales. ptt: me perdí ya que no agregaste en el
app.js el modelo de tvshow, luego tratas de hacer el tutorial que tienes hecho en youtube
y resulta que es de una versión antigua de express y tampoco funciona.
• •

VooDoo •

Hola Carlos, excelente tutorial! Me ha resultado muy muy util, funciona todo genial.

Aun asi, hay un pequeño detalle que no me va bien. Mi intencion es usar dos modelos a
la vez (en la misma base de datos). Comparandolo con tu caso seria base de datos
"tvshows" y modelos "tvshows" y "weather". Siguiendo tu ejemplo no parece complicado,
simplemente he añadido en el fichero "controllers/tvshows" la sentencia:

19 of 20 3/26/2016 11:18 PM
Aprende cómo crear un API REST usando Node.js, Express y MongoDB https://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

20 of 20 3/26/2016 11:18 PM

También podría gustarte