RESTful APIs, CRUD and Template Engine in Express.JS
RESTFul APIs
REST is the most common pattern followed while building APIs. When we are building APIs following REST pattern we call it RESTful APIs.
RE presentational S tate T ransfer is full form of REST. It a set of guidlines and best practices derived from Roy Fielding's original paper.
Representation and State refer how the server makes the data available. Transfer part talks about how it is sent back to the user.
- Use existing standards(HTTP, JSON, URL)
- Endpoints are collections of data
- Use GET, POST, PUT and DELETE to communicate the action that we are performing on that collection of data.
- Client and Server architecture.
- Our requests are both Stateless and cacheable. Stateless means every request is independent and not connected to any state on the client. We are only keeping track of data of the collections.
CRUD
It stands for Create Read Update Delete. Following are HTTP requests corresponding to each CRUD term :
Create - POST Read - GET Update - PUT Delete - DELETE
Sending files
Sending entire files that are present on our server machine back to the client.
We will use res.sendFile() to send the file and it takes the path of the file we want to send. sendFile needs to know the absolute path of the file.
We will use the in-built path module. We will use path.join() to combine the different components of our path.
__dirname is a built in variable which gets the folder name where the current file exists.
So __dirname will point to our controller folder. Now we need to go up in our folder structure to look for public file.
We will use '..' to tell node to look one directory up.
path.join(__dirname,'..','public', 'picture.jpg')
This line of code means a. look in the current folder b. go one level up in folder structure c. search for public folder d. look for picture.jpg.
Express will set up the content-type based on the extension of our file nae.
We can finally send the file using the .sendFile function
const path = require('path');
function getMessages(req, res){
res.sendFile(path.join(__dirname,'..','public', 'picture.jpg'))
}
Serving 1000s of files from our server
Serving Websites with Node
One way to serve a website containing HTML, images, pdfs and other stuffs is to use the express static file middleware .
We write the following code to use our middleware
app.use(express.static());
.static() takes the relative path of the folder that we want to make available from our server.
We will use our public folder which will have some html site in it. You can use any sample website in this folder.
app.use(express.static('public'));
Just like our endpoints we can mount our middleware on some site
app.use('/test',express.static('public'));
express.static takes a relative path specific to the folder from which we launch our node application.
So if we change the directory and then run ouur index file, our server will run but express won't be able to find the public folder.
We will use the path.join() function again.
app.use('/test',express.static(path.join(__dirname, 'public')));
So now .static() middleware is taking the absolute path now.
Template Engines
Handlebar is a more modern template engine based on the older mustache engine. It uses {{}} 'curly braces' as placeholder for variables.
Fundamentally all template engines are same using slightly different syntax
When we run our express server, the template engine replaces the variables marked with our curly braces with their actual values that come from the node server and it transforms the HTML document to an HTML file to be rendered by the browser. This allows us to populate our HTML with data before sending to the client to be shown to the user.
To use template engines we need to install npm packages.
For installing hbs we will use
npm i hbs --save
We don't need to import our template engines. We need to tell express which template engine we are using and where we are using it.
Go to the app.set() method in documentation of Express and look for view engine and views. These are our template engines.
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));
We made a views folder. Writing above two lines of code will tell express all the information it needs to load our handlebar internally and to find our templates in our project folder.
Move the index.html to views folder to comvert it to template.
Since we are using now handle bars and there will variables inside the index.html it is no more a pure .html file. Rename index.html to index.hbs .
After renaming it put variables in place of title and h1. The way we put variables here is in two curly brackets.
{{title}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel = 'stylesheet' href = '/css/style.css'/>
<title>{{title}}</title>
</head>
<body>
<h1>{{caption}}</h1>
<img src="./images/picture.jpg"/>
</body>
</html>
Now we will work in our index.js file and create a route for our index.hbs
app.get('/', (req, res) => {
res.render('index', {
title: 'Testing the HTML',
caption: 'Heyy it\'s working'
})
})
.render()
tells the express to render the handle bar file name 'index' and it will take an object that will contain the variable names as key and their value.
We made our static site rendering ar /test so we need to update the path in our img
and link
file to 'test' as well.
<link rel = 'stylesheet' href = 'test/css/style.css'/>
<img src="test/images/picture.jpg"/>
Note that we are rendering the static site at /test we will use the path as test/... if we rendered the static site at '/' we needed to specify the path like this
<img src="/images/picture.jpg"/>
Run the server and we will find the html page will load with our provided values of title and caption.