...
/Creating REST API for the Course Management Application
Creating REST API for the Course Management Application
Learn how to create a REST API for the course management application.
We'll cover the following...
- Setting up the token verification
- Creating the REST APIs for the course management application
- API to get all the created courses
- API to get a specific course
- API to add a new course
- API to update a specific course
- API to delete a specific course
- Configuring the REST API for the Course Management Application
To create the REST API for the course management app, we need to start by creating the verification token, which will help us authorize a user every time they request the client-side. The token will get sent to the server as an authorization header, and the server will then process the token and verify if it’s a valid one. If the token sent to the server is verified as correct, the API will grant the request. If not, an error will get returned.
Setting up the token verification
To set up the token verification middleware, we need to create a new file called verifyToken.js
in the middleware folder of our node.js application. We then proceed to type the code below inside our file:
const jwt = require('jsonwebtoken')module.exports = (req, res, next) => {const authHeader = req.headers.authorization;if (authHeader) {const token = authHeader.split(' ')[1];jwt.verify(token, process.env.JWT_SECRET_KEY, (err, user) => {if (err) {return res.sendStatus(403);}req.user = user;next();});} else {res.sendStatus(401);}};
In summary, what we did above was:
- In line 1, we import the
jsonwebtoken
npm package into ourverifyToken.js
file. - Next in line 3, we used the
module.exports
functionality that helps to export any function within it. - The
module.exports
was assigned a function with three arguments calledreq
,res
, andnext
. - In line 4, we create a variable called
authHeader
. This variable helps extract the bearer token passed when the request gets made using the REST API. - Next, in line 6, we create an
if
statement with the condition that if theauthHeader
which carries our token exists, then the logic between line 7 and line 13 should get executed. In a situation where