Express Web API
Nowadays, web api is one of the most popular topic in our mobile world. And with NodeJS together with express framework, defining a web api takes minutes.
Express framework initializer is very handy to create our example. To make use of it simply install it from npm. This will create express executable under /usr/bin/
Usage of express generator is also very easy. Execute the below command after installing express-generator and this will create the folder structure for you and some samples included to start your web application directly.
In this post, I am concentrating on API, so I haven’t provided a view engine for express. If I like to than all I need to do is call express like;
for pug view engine. I am planning to write another post for pug engine also but for now lets go back to our first web api with NodeJS and Express.
After executing the above command, it will create a folder called ‘firstapp’. Go to that directory and install the dependencies.
Now we are ready with our application, but we can remove some unnecessary files generated like CSS and default views, since we are creating a web api here.
The routing is already handled under app.js file that is generated and server creation is handled under bin/www file. So, now we are ready with our API structure. I am going to left the details of these files for another post.
The only remaining thing left is to write our first api GET method. This will be our welcome to our api. Under routes directory Here express generator already generated two routes for you, but this routes are trying to render a web page. We are going to deal with index.js and let users.js as it is.
Let’s change index.js with our favorite editor. (vim in my case) Edit this file like below;
After these changes, try your web api. Execute;
To see the output just browse http://localhost:3000
The default port for express generated application is 3000. If everything goes well, you should see something like this.
Let’s write our first post method also. So that we have the most common rest api calls in place. Open the index.js file and add the below code under our get method.
And you need to see an output like;
Lets also integrate one more thing to our api for fun. It is a good practice to measure your api performance at all times. There is a realy good and simple npm package (response-time) for NodeJS to accomplish this. Go to firstapi folder and execute;
This will install the response-time npm package and also update your package.json file. To make it work, open your app.js file and edit as follows;
After you restart your api (kill node and npm start) and call for your new get and post methods, you will see an additional header information that tells you the requests response time (cpu time). Here how your new header looks like;
The End for this post and thanks for reading. I know, we have gaps to still fill and you may have questions, please comment.