NodeJS API-Part 2 / Returning some fake data!
This is the 2º tutorial of a complete series of building a production “NodeJS API using Express, MySQL and Sequelize”.
Full source code of this class is available at GitHub Martial Arts API Part 2
RETURNING SOME JSON DATA
Now we will return some data in our server, for that you just need to modify a bit your app.js
file so it will look like this.
If you restart your server using Ctrl+C
(to exit) and then node app.js
(to start). Go to your browser and type http://localhost:8000/dojos
.
You will se a screen like that with your fake JSON data.
Well, it seems that your are getting there to build your API. This is fake data but you can already see what is going to happen.
EXPLANING THE CODE
If you didn’t understand our code I will explain it.
After starting our server on port 8000. We use our app variable with get to indicate that the following function will be executed if the user uses a GET
request.
app.get()
: expects two arguments, the first one is the endpoint where the user will access it. In our case the user will need to type base_url/dojos
. The second is a function which has two arguments, the request
(req) and the res
(response).
req
: Contain information about the user request, as query parameters, headers and etc.
res
: Let’s say in some informal words, this is your answers, I am going to use res to give a response to my user. That is why I use res.send()
to send our JSON Object to our user.
After that we just send a fake JSON Object which represent one of my dojos (dojo is a martial arts gym, for those who doesn’t know) and that is what the user see on the screen when he request the url.
IMPROVING OUR PROJECT
Not so hard until now. To improve our project we will download some things that will help us along our path.
- Postman: We will use this software to make our request, instead of doing so in the browser.
- Nodemon: We will use this to start our server instead of typing
node app.js
we will typenodemon app.js
.
Type npm install -g nodemon
on your visual code terminal to install it globally.
With nodemon we do not need to restart our server when we make changes, it restart automatically when we save.
Full source code of this class is available at GitHub Martial Arts API Part 2