Loopback with Node.js and MongoDB
Do you like the idea to have an auto documented API, with the capacity to test it directly from the documentation? You can have it with the Swagger, or in this case, with Loopback based on Node.js that we are going to review in this post. If like this idea, keep reading, and stay we me that we are ready to start!
Step 00: Installing Loopback
Loopback is similar to swagger, a very nice tool to describe an API REST, and it is based on Node.js
I will use a new dir
The command to install strongloop and loopback is:
$ npm install -g strongloop
Step 01: Creating an App with Loopback CLI
Let’s create the app with the Loopback CLI (Command Line Interface)
$ slc loopback todo
From an empty dir, loopack built the followings dirs:
Let’s create the model (cat and cats)
$ slc loopback:model
Step 02: Starting the App created with Loopback
Let’s start the app:
And when we browse
we can see the browser api explorer
Let insert one or two cats:
cat 1: “Ramoncito”
I get the error because we don’t have the datasource attached:
“Cannot call cat.replaceOrCreate(). The replaceOrCreate method has not been setup. The PersistedModel has not been correctly attached to a DataSource!”,
Step 03: Database Integration (MongoDB connector)
The MongoDB connector to Looback 3.x that I am using is
MongoDB connector | LoopBack Documentation
The MongoDB connector enables LoopBack applications to connect to MongoDB data sources.
$ npm install loopback-connector-mongodb --save
we will edit the server/datasources.json file
Step 04: Test the API Rest (CRUD Operations)
Un GET cats and an empty response, that it is good: we don’t have db errors!
Let’s insert a Cat with the POST:
OK! we have a good response:
Let’s do the GET again:
Step 05: Database Integration (GUI)
I made a mistake with “cat” and “cats” api … I would have to reuse my existing API… with in this example I made a mistake… model “cat” instead “cats”, according to the API best practices:
¿The Endpoint Name in the API Design, should be singular o plural?
keep-it-simple: siempre plural: evita lidiar con plurales irregulares (person/people, goose/geese) y modernos frameworks generarán de esa manera: /tickets y /tickets/12. (1)
Ok… I will end the post at this point
We have been able to build a working backend node.js app with loopback and connected to a mongo db database
I hope this post help you to learn something new, and to not be afraid about try different ways to develop software!
See you in another one!
- A good post that I was reading while I was writing this one: Comparing Express, Restify, hapi and LoopBack for building RESTful APIs
- A resume about Good practices on API design