Servidor API REST con Node.js

56
SERVIDOR API REST CON NODE.JS ADOLFO SANZ DE DIEGO OCTUBRE 2013

description

Creando un servidor con una API RESTful con nodejs, expressjs and mongoosejs.

Transcript of Servidor API REST con Node.js

Page 1: Servidor API REST con Node.js

SERVIDORAPIRESTCONNODE.JS

ADOLFOSANZDEDIEGOOCTUBRE2013

Page 2: Servidor API REST con Node.js

1ACERCADE

Page 3: Servidor API REST con Node.js

1.1ELGULElGULeselGrupodeUsuariosdeLinuxdelaUC3M.Grupodepersonasconinquietudesentornoalainformática.ConlaideacomúndelautilizaciónypromocióndelSoftwareLibre.Quedamosdevezencuandoyorganizamosactividadessobretodoesto.Elpuntodeunióneslalistadecorreoqueestáabiertaatodoelmundo.

Page 4: Servidor API REST con Node.js

1.2¿DÓNDEENCONTRARNOS?Twitter:Lista:Ftp:Web:Podcast:Blog:Linkedin:

http://twitter.com/[email protected]

ftp://ftp.gul.uc3m.eshttp://www.gul.uc3m.es

http://holamundo.gul.es/http://planeta.gul.uc3m.es/

http://www.linkedin.com/groups?gid=3451836

Page 5: Servidor API REST con Node.js

1.3ADOLFOSANZDEDIEGOAntiguoprogramadorwebJEEHoyendía:ProfesordeFPdeinformática:Hardware,SistemasOperativosRedes,Programación

FormadorFreelance:Java,AndroidJavaScript,jQueryJSF,Spring,HibernateGroovy&Grails

Megustaprogramar

Page 6: Servidor API REST con Node.js

1.4HACKALOVER

ParalosamantesdeloshackathonesMeetup:

Twitter:Blog:LinkedIn:

YouTube:

http://www.meetup.com/Hackathon-Lovers/

http://twitter.com/HackathonLovershttp://hackathonlovers.tumblr.com/

http://www.linkedin.com/groups/Hackathon-Lovers-6510465

http://www.youtube.com/channel/UCRwSe7jK-y62BMvIiNBV1qw

Page 7: Servidor API REST con Node.js

1.5TWEETSSENTIMENT

Esunanalizadordetweetsqueextraeinformaciónsemánticaparaconocersielsentimientogeneraldelostweetsdeundeterminadotemaespositivoonegativo.Web:Twitter:

http://tweetssentiment.com/http://twitter.com/TweetsSentiment

Page 8: Servidor API REST con Node.js

1.6¿DONDEENCONTRARME?Minick:asanzdiegoAboutMe:GitHub:Twitter:Blog:LinkedIn:Google+:

http://about.me/asanzdiegohttp://github.com/asanzdiegohttp://twitter.com/asanzdiego

http://asanzdiego.blogspot.com.eshttp://www.linkedin.com/in/asanzdiego

http://plus.google.com/+AdolfoSanzDeDiego

Page 9: Servidor API REST con Node.js

1.7CRÉDITOSAgradecimientosaCarlosAzustre( )CómocrearunaAPIRESTusandoNode.JS

Estastransparenciasestánhechascon:

http://twitter.com/carlosazaustre

http://carlosazaustre.es/blog/como-crear-una-api-rest-usando-node-js/

https://github.com/asanzdiego/markdownslides

Page 10: Servidor API REST con Node.js

1.8LICENCIAEstastransparenciasestánbajounalicencia:

Elcódigodelosprogramasestánbajounalicencia:

CreativeCommonsReconocimiento-CompartirIgual3.0

GPL3.0

Page 11: Servidor API REST con Node.js

1.9FUENTESTransparencias:

Código:

SlideShareDeckSlidesRevealSlidesPlainHTML

https://github.com/asanzdiego/curso-api-restful-nodejs-server-2013/tree/master/src

Page 12: Servidor API REST con Node.js

2APIS¿PARAQUÉ?

Page 13: Servidor API REST con Node.js

2.1APLICACIÓNESTÁNDAR

Page 14: Servidor API REST con Node.js

2.2INTRODUCIMOSAPI

Page 15: Servidor API REST con Node.js

2.3SEPARACIÓNROLES

Page 16: Servidor API REST con Node.js

2.4¿YAHORAQUÉ?

Page 17: Servidor API REST con Node.js

2.5SERVICIOSEXTERNOS

Page 18: Servidor API REST con Node.js

2.6APPSCLIENTES

Page 19: Servidor API REST con Node.js

2.7APPSDESERVICIOS

Page 20: Servidor API REST con Node.js

2.8APPSMIXTAS

Page 21: Servidor API REST con Node.js

2.9PLATAFORMA

Page 22: Servidor API REST con Node.js

2.10¿QUIENEXPONEAPIS?

Page 23: Servidor API REST con Node.js

2.11¿QUIENEXPONEAPIS?

Page 24: Servidor API REST con Node.js

2.12¿QUIENEXPONEAPIS?

Page 25: Servidor API REST con Node.js

2.13EXPONLASTÚ

Page 26: Servidor API REST con Node.js

2.14EXPONLASTÚ

Page 27: Servidor API REST con Node.js

2.15EXPONLASTÚ

Page 28: Servidor API REST con Node.js

3APISRESTFUL

Page 29: Servidor API REST con Node.js

3.1¿QUÉESREST?REST(RepresentationalStateTransfer)esunatécnicadearquitecturadesoftwareparasistemashipermediadistribuidoscomolaWorldWideWeb.EnRESTunaURL(UniformResourceLocator)representaunrecurso.SepuedeaccederalrecursoomodificarlomediantelosmétodosdelprotocoloHTTP:

GET,POST,PUT,DELETE

Page 30: Servidor API REST con Node.js

3.2EJEMPLOAPIhttp://myhost.com/talkGET>Devuelvetodaslascharlas.POST>Crearunanuevacharla.

http://myhost.com/talk/123GET>Devuelvelacharlaconid=123PUT>Actualizalacharlaconid=123DELETE>Borralacharlaconid=123

Page 31: Servidor API REST con Node.js

3.3MANEJODEERRORESSepuedenutilizarloserroresdelprotocoloHTTP:200Successful201Created202Accepted301MovedPermanently400BadRequest401Unauthorised402PaymentRequired403Forbidden404NotFound405MethodNotAllowed500InternalServerError501NotImplemented

Page 32: Servidor API REST con Node.js

3.4¿PORQUÉREST?Esmássencillo(tantolaAPIcomolaimplementación).Esmásrápido(peticionesmáslijerasquesepuedencachear).Esmultiformato(HTML,XML,JSON,etc.).SecomplementamuybienconAJAX.

Page 33: Servidor API REST con Node.js

3.5RESTVSRESTFULRESTserefiereauntipodearquitecturadesoftwareSeutilizacomonombreSeutilizacomoporejemplo:success=éxito.

SiunserviciowebesRESTfulindicaqueimplementadichaarquitectura.SeutilizacomoadjetivoSeutilizacomoporejemplo:successful=éxitoso).

Page 34: Servidor API REST con Node.js

3.6RESTVSRESTFULAveceselfulseconfundeconfull=completo.YserefierealosservicioswebRESTfull

YserefierealosservicioswebREST(sinelfull)

AquellosqueimplementanunaAPIcontodoslosmétodosdelprotócoloHTTP.

AquellosqueNOimplementanunaAPIcontodoslosmétodosdelprotócoloHTTP.

Page 35: Servidor API REST con Node.js

4NODE.JS

Page 36: Servidor API REST con Node.js

4.1INTRODUCCIÓN

Node.jspermiteprogramarenJavascriptdelladodelservidor.PensadoparaunmanejodeE/Sorientadaaeventos.

Page 37: Servidor API REST con Node.js

4.2EJECUCIÓNEjecuciónconcurrenteMuchostareas

PeroNOparaleloUnaúnicahebra

Page 38: Servidor API REST con Node.js

4.3¿DÓNDEUSARLO?CuandohaymuchaE/SyportantomuchaCPUinactivaportarea.

YhaymuchosclientesquecompensanesainactividaddelaCPU.

Pensadoparalacreacióndeprogramasderedaltamenteescalables.

Page 39: Servidor API REST con Node.js

4.4OTROSCONCEPTOSnpm :eselgestordepaquetesdeNode.js.

expressjs :esunalibreríaparaNode.jsdedesarrolloweb.

mongoosejs :esunalibreríaparaNode.jsdemodeladodeobjetosdeMongoDB

http://npmjs.org/

http://expressjs.com/

http://mongoosejs.com/

http://www.mongodb.org/

Page 40: Servidor API REST con Node.js

4.5PRIMEROPASOSInstalarNode.js

InstalarMongoDBhttp://nodejs.org/download/

http://docs.mongodb.org/manual/installation/

Page 41: Servidor API REST con Node.js

4.6ABURRIDO

Page 42: Servidor API REST con Node.js

5CÓDIGO

Page 43: Servidor API REST con Node.js

5.1APLAUSOS

Page 44: Servidor API REST con Node.js

5.2PACKAGE.JSONDefinelasdependenciasdenuestroproyecto.

{"name":"api-restful-nodejs-server","version":"0.0.1","dependencies":{"express":"3.x","mongoose":"3.6.20"}}

Page 45: Servidor API REST con Node.js

5.3NPMINSTALLEstecomandoinstalaráenlacarpetanode_moduleslasdependenciasdenuestroproyecto.

npminstall

Page 46: Servidor API REST con Node.js

5.4APP.JSEselficheroprincipal.Elnombreeslodemenos.Avecestambiénselesuelellamarserver.jsParaejecutarunaaplicacióndeNode.js:

nodeapp.js

Page 47: Servidor API REST con Node.js

5.5APP.JS//modulosrequeridosvarhttp,express,mongoose,app,server...

//configuramosappapp.configure(function(){//config...});

//importamoslasrutasvarroutes=require('./routes/talkRoute')(app);

//conectamosconlabasededatosmongoose.connect('mongodb://localhost/gul',function(err,res){//console.log('ConnectedtoGULMongoDBDatabase');});

//arrancamoselservidorserver.listen(3000,function(){//console.log("Serverrunningonhttp://localhost:3000");});

Page 48: Servidor API REST con Node.js

5.6DIRECTORIOSPuedesusarlaestructuradedirectoriosquequieras.Yoheusadoesta:models:routes:services:

Page 49: Servidor API REST con Node.js

5.7MODELSDirectorioconlosmodelosquesevanaguardarenbasededatos.Yocreounficherojsparacadacolección.

Page 50: Servidor API REST con Node.js

5.8MODELS/TALKMODEL.JS//modulosrequeridosvarmongoose=require('mongoose');varSchema=mongoose.Schema;

//definimoselmodelo'talk'consusrestricciones//tambiénpodemosdefinirrelacionesconotrosmodelos//aquínosehahechoporsimplificarvartalkSchema=newSchema({talkName:{type:String,required:true},talkDate:{type:Date,required:true},talkSpeaker:{type:String,required:true},talkSpeakerMail:{type:String,required:true,match:/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/},talkPoints:{type:Number,required:true,default:0}});

//exportamoselmodelomodule.exports=mongoose.model('Talk',talkSchema);

Page 51: Servidor API REST con Node.js

5.9ROUTESDirectorioconlosmapeosdelasrutasdelaAPIRESTful.Aquísólogestionola'request'yel'response'.Transformola'request'enunobjeto'options'yselepasoaunservicio.Loquedevuelvaelserviciolometoenel'response'.Yocreounficherojsparacadacolección.

Page 52: Servidor API REST con Node.js

5.10ROUTES/TALKROUTE.JSmodule.exports=function(app){

varTalkService=require('../services/talkService.js');

varfindTalks=function(req,res){TalkService.findAllTalks({...});};varfindTalk=function(req,res){vartalkId=req.params.talkId;TalkService.findTalkById({...});};varaddTalk=function(req,res){...};varupdateTalk=function(req,res){...};vardeleteTalk=function(req,res){...};

//mapeamosmétodoyURLaunafunciónapp.get('/talk',findTalks);app.get('/talk/:talkId',findTalk);app.post('/talk',addTalk);app.put('/talk/:talkId',updateTalk);app.delete('/talk/:talkId',deleteTalk);}

Page 53: Servidor API REST con Node.js

5.11SERVICESAquíestánlosserviciosqueaccedenabasededatos.Aquínohaynirequestniresponse.Lasfuncionesrecibenunobjeto'options'conloquenecesita.Normalmentedebengestionaralmenosun'onSuccess'yun'onError'.Hayfuncionesqueademásgestionanun'onNotFound'.Unserviciopuedellamaraotrosservicios.Yocreounficherojsparacadacolección.

Page 54: Servidor API REST con Node.js

5.12SERVICES/TALKSERVICE.JS//importamoselmodelovarTalk=require('../models/talkModel.js');

varfindAllTalks=function(options){Talk.find(function(error,talks){...});};varfindTalkById=function(options){Talk.findById(options.talkId,function(error,talk){...});};varsaveTalk=function(options){...};varfindTalkByIdAndUpdate=function(options){...};varfindTalkByIdAndRemove=function(options){...});

//exportamoslosserviciosexports.findAllTalks=findAllTalks;exports.findTalkById=findTalkById;exports.saveTalk=saveTalk;exports.findTalkByIdAndUpdate=findTalkByIdAndUpdate;exports.findTalkByIdAndRemove=findTalkByIdAndRemove;

Page 55: Servidor API REST con Node.js

6DEMO

Page 56: Servidor API REST con Node.js

7¿ALGUNAPREGUNTA?